<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.png">
  <link rel="mask-icon" href="/images/avatar.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notes.maxwi.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":true,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="关于本文主要是看《C++ primer》时的总结，由于以前学习过C++，所以仅仅记录了自己忘记的以及一些之前没有弄明白的东西。本文举例全部通过gcc 5.1.2验证，使用g++编译进可以通过指定-std&#x3D;c++11或-std&#x3D;c++0x来启用对C++11的支持。eg: g++ -o hello hello.cpp -std&#x3D;c++11 -Wall，-Wall是开启警告。参考手册：1.cpluspl">
<meta property="og:type" content="article">
<meta property="og:title" content="C++学习笔记之基础">
<meta property="og:url" content="http://notes.maxwi.com/2015/06/22/cpp-study-notes/index.html">
<meta property="og:site_name" content="blueyi&#39;s notes">
<meta property="og:description" content="关于本文主要是看《C++ primer》时的总结，由于以前学习过C++，所以仅仅记录了自己忘记的以及一些之前没有弄明白的东西。本文举例全部通过gcc 5.1.2验证，使用g++编译进可以通过指定-std&#x3D;c++11或-std&#x3D;c++0x来启用对C++11的支持。eg: g++ -o hello hello.cpp -std&#x3D;c++11 -Wall，-Wall是开启警告。参考手册：1.cpluspl">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2015-06-22T10:58:45.000Z">
<meta property="article:modified_time" content="2015-06-22T10:58:45.000Z">
<meta property="article:author" content="blueyi">
<meta property="article:tag" content="Notes">
<meta property="article:tag" content="CPP">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://notes.maxwi.com/2015/06/22/cpp-study-notes/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>C++学习笔记之基础 | blueyi's notes</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="blueyi's notes" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="blueyi's notes" type="application/rss+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">blueyi's notes</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Follow Excellence,Success will chase you!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://notes.maxwi.com/2015/06/22/cpp-study-notes/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/default_avatar.jpg">
      <meta itemprop="name" content="blueyi">
      <meta itemprop="description" content="心怀善意，虛怀若谷！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="blueyi's notes">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          C++学习笔记之基础
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2015-06-22 18:58:45" itemprop="dateCreated datePublished" datetime="2015-06-22T18:58:45+08:00">2015-06-22</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/" itemprop="url" rel="index"><span itemprop="name">C++</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="Symbols count in article">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">Symbols count in article: </span>
              <span>52k</span>
            </span>
            <span class="post-meta-item" title="Reading time">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">Reading time &asymp;</span>
              <span>48 mins.</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="关于本文"><a href="#关于本文" class="headerlink" title="关于本文"></a>关于本文</h1><p>主要是看《C++ primer》时的总结，由于以前学习过C++，所以仅仅记录了自己忘记的以及一些之前没有弄明白的东西。本文举例全部通过gcc 5.1.2验证，使用g++编译进可以通过指定<code>-std=c++11</code>或<code>-std=c++0x</code>来启用对C++11的支持。eg: <code>g++ -o hello hello.cpp -std=c++11 -Wall</code>，<code>-Wall</code>是开启警告。<br>参考手册：<br>1.cplusplus Reference，包含了C++和C的标准库，并带有示例： <a target="_blank" rel="noopener" href="http://www.cplusplus.com">http://www.cplusplus.com</a><br>2.cppreference配全上面使用，该站点有中文版本：<a target="_blank" rel="noopener" href="http://www.cppreference.com">http://www.cppreference.com</a><br>其他资料：<br>1.C++中指针和引用的区别：<a target="_blank" rel="noopener" href="http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in">http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in</a><br>2.<code>const int*</code>、<code>const int * const</code>、<code>int const *</code>的区别：<a target="_blank" rel="noopener" href="http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const">http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const</a><br>3.什么是C++11中的<code>rvalue</code>、<code>lvalue</code>、<code>xvalue</code>、<code>glvalue</code>、<code>prvalue</code>：<a target="_blank" rel="noopener" href="http://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues">http://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues</a>   </p>
<span id="more"></span>  
<p>4.使迭代器失效的规则解释：<a target="_blank" rel="noopener" href="http://stackoverflow.com/questions/6438086/iterator-invalidation-rules">http://stackoverflow.com/questions/6438086/iterator-invalidation-rules</a>   </p>
<h1 id="基础知识"><a href="#基础知识" class="headerlink" title="基础知识"></a>基础知识</h1><p>1.注释与”交替出现时，谁在前面先匹配谁：<br><code>std::cout &lt;&lt; /* &quot;*/&quot; /* &quot;/*&quot; */;</code>输出为<code>/*</code>，因为出现<code>/*</code>时后面的第一个<code>*/</code>会自动与其匹配，然后<code>&quot;</code>出现时它会与后面的第一个<code>&quot;</code>进行匹配。注释会被编译器直接忽略掉。  </p>
<p>2.以下输出结果为2^32 - 32  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">unsigned</span> a = <span class="number">10</span>, b = <span class="number">42</span>;</span><br><span class="line">std::cout &lt;&lt; a - b &lt;&lt; std::endl;</span><br></pre></td></tr></table></figure>

<p>3.C++支持的4种变量初始化的方法：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">a</span><span class="params">(<span class="number">1</span>)</span></span>;</span><br><span class="line"><span class="comment">//以下仅在C++11中支持，好处之一是当变量无法容纳初始值时不会进行强制类型转换</span></span><br><span class="line"><span class="type">int</span> a = &#123;<span class="number">1</span>&#125;;</span><br><span class="line"><span class="type">int</span> a&#123;<span class="number">1</span>&#125;;</span><br></pre></td></tr></table></figure>

<p>1.通常标准库的头文件使用尖括号<code>&lt;&gt;</code>，非标准库的头文件使用双引号””。</p>
<p>2.函数体外的变量会被自动初始化为0，函数体内的变量不会被自动初始化。</p>
<p>3.extern 可用于声明该变量在其他地方有定义(extern int a;)，或者可以在函数外部定义全局变量(extern int a = 10;)。</p>
<p>4.定义const变量(常量)必须在定义时初始化。如果const变量不是用常量表达式初始化，不应该将其在头文件中定义，该const变量应该在一个源文件中定义并初始化，并在头文件中为它添加extern声明，以使其能被多个文件共享。</p>
<p>7.头文件应该用于声明而不是定义，<code>extern int ival = 10;</code>和<code>double cash;</code>都属于定义。但头文件中可以定义类、值在编译时就已经知道的const对象和inline函数。</p>
<p>8.通过定义预处理器变量来避免重复包含头文件。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">ifndef</span> HELLO_H   <span class="comment">//测试是否定义该预处理器变量，若没有定义，则后面的所有定义都执行，直到#endif</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> HELLO_h</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">Sales_item</span> &#123;</span><br><span class="line">    std::string bookNo;</span><br><span class="line">    <span class="type">unsigned</span> units_sold = <span class="number">0</span>;</span><br><span class="line">    <span class="type">double</span> revenue = <span class="number">0.0</span>;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br></pre></td></tr></table></figure>

<p>9.引用的定义方式为<code>int &amp;a = b;</code>表示 a是b的别名。</p>
<h1 id="string"><a href="#string" class="headerlink" title="string"></a>string</h1><p>10.string类型与字符串字面值类型不同。string有以下几种初始化方式：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">string str; str = <span class="string">&quot;&quot;</span>;</span><br><span class="line"><span class="function">string <span class="title">str</span><span class="params">(s1)</span></span>;str = s1;</span><br><span class="line"><span class="function">string <span class="title">str</span><span class="params">(<span class="string">&quot;hello&quot;</span>)</span></span>;str = <span class="string">&quot;hello&quot;</span>;</span><br><span class="line"><span class="function">string <span class="title">str</span><span class="params">(<span class="number">4</span>,<span class="string">&#x27;l&#x27;</span>)</span></span>;str = <span class="string">&quot;llll&quot;</span>;</span><br></pre></td></tr></table></figure>

<p>11.string类型的输入操作符会读取并忽略有效字符前的的所有空白字符，如空格、换行符、制表符。读取字符直到再次遇到空白字符，读取终止，且该空白字符仍在输入流中。</p>
<p>12.getline(cin, line) 一次读取一行，且不忽略开头的空白字符，遇到换行符终止并丢弃换行符（此时换行符不在输入流中），返回一个istream引用。如果这个返回值作为if或者while等的bool逻辑判断，则读取成功返回true，失败返回false，所以<code>istream&amp; getline(istream&amp; in, string &amp; str, char delim = &#39;\n&#39;)</code>函数可以使用while循环进行判断。</p>
<p>13.string类的s.size()/length()返回s中英文字符个数或者字节数，返回值为string::size_type类型，该类型与unsigned类型具有相同的含义，不能将其赋给int类型。s.empty()测试s是否为空。</p>
<p>14.string对象使用+操作符与字符串字面值进行连接时左右操作数必须至少有一个是string对象，注意str1+str2返回的是一个string对象。所以这个是非法的<code>string str = &quot;Hello&quot; + &quot;world&quot; + s1;</code>，而这两种是合法的<code>string str = s1 + &quot;Hello&quot; + &quot;world&quot;;string str =  &quot;Hello&quot; +s1 + &quot;world&quot;;</code>。另外注意<code>string str = &quot;Hello&quot;;</code>是一个赋值初始化的过程，构造初始化应为<code>string str(&quot;Hello&quot;);</code>。</p>
<p>15.cctype标准库头文件中测试函数返回的是int类型值，测试失败返回0，测试为真返回非0;其中的tolower()和toupper()返回也为int，即对应字符的ASCII码，其中还包含了isalnum(),isalpha()等。</p>
<p>16.C++通过cstring头文件提供对C语言风格的字符串操作。如<code>strlen(s), strcmp(s1, s2), strcat(s1, s2), strcpy(s1, s2), strncat(s1, s2, n), strncpy(s1, s2,n)</code>。其中strn类的函数更安全，它能够控制复制字符的个数。strlen返回的是字符个数，不包括null结束符。处理C风格字符串时一定要记得字符串结束符null。尽量避免使用C风格字符串而是使用标准库类型string，其安全性和效率更高。可以使用C风格字符串初始化string，但不能使用string直接初始化C风格字符串，但string类提供的c_str()函数可以返回一个const类型的C风格字符串。</p>
<p>17.C++11中可以使用范围for，即range for来遍历给定序列中的每个元素，并对该元素进行操作，<code>for (declaration : expression)&#123;&#125;</code>。<br>注意默认情况下范围for使用的是非引用的方式访问序列中的元素，所以此时无法修改序列中的元素，如果需要修改序列中的元素，则必须使用引用。<br>eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">string <span class="title">str</span><span class="params">(<span class="string">&quot;Hello world!!!&quot;</span>)</span></span>;</span><br><span class="line"><span class="comment">//punct_cnt的类型将与str.size()类型一致，都是string:size_type  </span></span><br><span class="line"><span class="keyword">decltype</span>(str.<span class="built_in">size</span>()) punct_cnt = <span class="number">0</span>;</span><br><span class="line"><span class="comment">//使用auto来让编译器自动判断所需类型</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">auto</span> c : str) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">ispunct</span>(c))</span><br><span class="line">      ++punct_cnt;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//输出标点符号的个数</span></span><br><span class="line">cout &lt;&lt; punct_cnt &lt;&lt; endl;</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用引用c访问每个字符并将其改成大写</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">auto</span> &amp;c : str) &#123;</span><br><span class="line">    c = <span class="built_in">toupper</span>(c);</span><br><span class="line">&#125;</span><br><span class="line">cout &lt;&lt; str &lt;&lt; endl;</span><br></pre></td></tr></table></figure>

<p>18.注意char *字义的字符串与string并不一样，char *字义的字符串是常量字符串，无法修改它们的值，如<code>char *str = &quot;Hello world&quot;</code>，此时str是只读的。  </p>
<h2 id="C-11下的字符串数组"><a href="#C-11下的字符串数组" class="headerlink" title="C++11下的字符串数组"></a>C++11下的字符串数组</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">char</span> *str = <span class="string">&quot;abc&quot;</span>; <span class="comment">//C++11下会出现警告，因为这相当于将一个可变的指针，绑定到一个字符面值常量  </span></span><br><span class="line"><span class="type">const</span> <span class="type">char</span> *str1 = <span class="string">&quot;abc&quot;</span>; <span class="comment">//正确  </span></span><br><span class="line"><span class="type">char</span> str2[] = <span class="string">&quot;abc&quot;</span>;  <span class="comment">//声明一个数组，当然没有问题</span></span><br></pre></td></tr></table></figure>


<h1 id="vector"><a href="#vector" class="headerlink" title="vector"></a>vector</h1><p>16.vector是同一种类型的对象的集合，是一个类模板，可以定义任意多种数据类型，定义方法为<code>vector&lt;type&gt; variable_list;</code>，意为vector<type>类型的var。它与数组极为相似。vector能容纳绝大多数类型的对应作为其元素，但引用不是对象，所以引用不能作为其原素，vector的元素本身也可以是vector,eg: <code>vector&lt;vector&lt;string&gt;&gt; vstr;//需要C++11</code>如果编译器不支持，需要在后面尖括号中加一个空格，如<code>vector&lt;vector&lt;string&gt; &gt; vstr;</code></p>
<p>17.所有模板的实例化方法都是在模板名字后面跟一对尖括号，在括号中放入实例化信息。  </p>
<p>17.初始化vector对象的方法：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">vector&lt;T&gt;  v1;  <span class="comment">//vector保存类型为T的对象，默认构造函数v1为空。</span></span><br><span class="line"><span class="function">vector&lt;T&gt; <span class="title">v2</span><span class="params">(v1)</span></span>;  <span class="comment">//v2是v1的一个副本。</span></span><br><span class="line">vector&lt;T&gt; v2 = v1;  <span class="comment">//等价于v2(v1);</span></span><br><span class="line"><span class="function">vector&lt;T&gt; <span class="title">v3</span><span class="params">(n, i)</span></span>;  <span class="comment">//v3包含n个值为i的元素。eg:`vector&lt;int&gt; vec(10, 2);` 10元素，每个元素都被初始化为2。</span></span><br><span class="line"><span class="function">vector&lt;T&gt; <span class="title">v4</span><span class="params">(n)</span></span>;  <span class="comment">//v4含有类型T默认的值初始化的元素的n个副本。</span></span><br><span class="line">vector&lt;T&gt; v5&#123;a,b,c...&#125;; <span class="comment">//v5包含初始值个数的元素，每个元素被赋予相应的初始值，需要C++11的支持  </span></span><br><span class="line">vector&lt;T&gt; v5 = &#123;a,b,c...&#125;; <span class="comment">//等价于v5&#123;a,b,c...&#125;</span></span><br></pre></td></tr></table></figure>

<p>18.vector初始化时应尽量使用()指定vector中的元素数量，而使用{}指定初始值,eg:   </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">v1</span><span class="params">(<span class="number">10</span>, <span class="number">12</span>)</span></span>; <span class="comment">//10个元素，每个元素值都是12</span></span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">v2</span><span class="params">(<span class="number">10</span>)</span></span>; <span class="comment">//10个元素，每个元素值都是0</span></span><br><span class="line">vector&lt;<span class="type">int</span>&gt; v3; <span class="comment">//0个元素</span></span><br><span class="line"><span class="function">vector&lt;string&gt; <span class="title">v4</span><span class="params">(<span class="number">10</span>, <span class="string">&quot;hi&quot;</span>)</span></span>; <span class="comment">//10个元素，每个元素值都是“hi”</span></span><br><span class="line">vector&lt;string&gt; v5&#123;<span class="number">10</span>, <span class="string">&quot;hi&quot;</span>&#125;; <span class="comment">//10个元素，每个元素值都是“hi”</span></span><br><span class="line">vector&lt;string&gt; v6&#123;<span class="number">10</span>&#125;; <span class="comment">//10个元素，每个元素值都是“”</span></span><br></pre></td></tr></table></figure>

<p>17.vector对象支持的操作：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">v.<span class="built_in">empty</span>();  <span class="comment">//v为空返回true</span></span><br><span class="line">v.<span class="built_in">size</span>();  <span class="comment">//v中元素个数</span></span><br><span class="line">v.<span class="built_in">push_back</span>(t);  <span class="comment">//将t插入到v的末尾</span></span><br><span class="line">v[n];  <span class="comment">//返回v中位置为n的元素</span></span><br><span class="line">v1 =  v2;  <span class="comment">//把v1中的元素替换为v2中元素的副本。</span></span><br></pre></td></tr></table></figure>
<p>==, !=, &lt;, &lt;=, &gt;, &gt;=保持其操作符惯有的含义。</p>
<p>18.vector可以动态的增加元素。对vector中各元素的访问与对string中各字符的访问方法一样使用下标，为vector对象增加一个元素需要使用<code>v.push_back(t);</code>。v.size()的返回类型与string也类似为vector<T>::size_type。</p>
<p>19.C++由于可以使用内联函数，所以在每次的循环测试中都直接使用v.size()不会增加太多运行代价。</p>
<p>20.string和vector对象在没有定义确定元素时都无法通过下标直接增加值，string只能使用+操作符，vector只能使用v.push_back(t)。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">string str1 = <span class="string">&quot;Hello world!&quot;</span>;</span><br><span class="line">string str2;</span><br><span class="line"><span class="keyword">for</span>(string::size_type ix = <span class="number">0</span>; ix != str1.<span class="built_in">size</span>(); ++ix)</span><br><span class="line">&#123;</span><br><span class="line">    str2[i++] = str1[ix];  <span class="comment">//Error,str2元素个数为0;</span></span><br><span class="line">    str2 += str1[ix];    <span class="comment">//OK</span></span><br><span class="line">&#125;</span><br><span class="line">vector&lt;<span class="type">int</span>&gt; num;</span><br><span class="line"><span class="keyword">for</span> (vector&lt;<span class="type">int</span>&gt;::size_type ix = <span class="number">0</span>; ix &lt; <span class="number">10</span>;++ix)</span><br><span class="line">&#123;</span><br><span class="line">    num[ix] = ix; <span class="comment">//Error,num[ix]处的元素并不存在，下标只能访问已经存在的元素</span></span><br><span class="line">    num.<span class="built_in">push_back</span>(ix);  <span class="comment">//OK</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="迭代器iterator"><a href="#迭代器iterator" class="headerlink" title="迭代器iterator"></a>迭代器iterator</h1><p>21.标准库为每一种容器类型都定义了一种迭代器iterator类型。迭代器比下标访问元素更通用化。它与指针非常相似，C++中的容器有:<br>顺序性容器:<br>vector: 从后面快速的插入与删除，直接访问任何元素<br>deque: 从前面或后面快速的插入与删除，直接访问任何元素<br>list: 双链表，从任何地方快速插入与删除<br>关联容器:<br>set: 快速查找，不允许重复值<br>multiset: 快速查找，允许重复值<br>map: 一对多映射，基于关键字快速查找，不允许重复值<br>multimap: 一对多映射，基于关键字快速查找，允许重复值<br>容器适配器:<br>stack: 后进先出<br>queue: 先进先出<br>priority_queue: 最高优先级元素总是第一个出列<br>关于容器的两个讨论：<a target="_blank" rel="noopener" href="http://www.tuicool.com/articles/aiMnAz">http://www.tuicool.com/articles/aiMnAz</a>和<a target="_blank" rel="noopener" href="http://www.cnblogs.com/answeryi/archive/2011/12/16/2289811.html">http://www.cnblogs.com/answeryi/archive/2011/12/16/2289811.html</a><br>注意虽然string不是迭代器，但string支持迭代器  </p>
<p>22.迭代器类型的定义方式为vector<int>::iterator iter;(以vector为例)，其定义了一个vector<int>::iterator类型的迭代器变量。  </p>
<p>23.每一种容器都定义一对命名为begin和end的函数，用于返回迭代器。如果容器中有元素则begin返回的迭代器指向第一个元素。end函数返回的是容器的最后一个元素的下一个，它指向的是一个不存在的元素。如果容器为空，则begin与end相同。<br>eg:<code>vector&lt;int&gt;::iterator iter = ivec.begin();</code>//iter初始化为由为begin的vector操作返回的值。如果ivec不为空，则iter指向元素为ivec[0],iter就像指向容器中元素的指针。如果iter指向ivec的第一个元素，则*iter与ivec[0]指向就是同一个元素，iter支持++,–操作符。</p>
<p>24.迭代器可以使用==或者!=进行比较，如果两个迭代器指向同一个元素则相等。</p>
<p>25.iter-&gt;mem 表示解引用iter并获取该元素的名为mem的成员，等价于(<em>iter).mem，例如对于string的vector中元素支持的empty()函数，(</em>.ter).empty() &lt;=&gt; ter-&gt;empty()  </p>
<p>26.由于所有标准库容器的迭代器都定义了==和!=操作符，所以可以养成使用!=和迭代器而不是<code>&lt;</code>和下标的习惯。  </p>
<p>25.每一种迭代器的const_iterator类型只能用于读取它所指向元素的值，不能写,相当于常量指针。begin和end返回值是不是常量由对象是不是常量决定。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">vector&lt;<span class="type">int</span>&gt; v;</span><br><span class="line"><span class="type">const</span> vector&lt;<span class="type">int</span>&gt; cv;</span><br><span class="line"><span class="keyword">auto</span> it1 = v.<span class="built_in">begin</span>();  <span class="comment">//it1的类型是vector&lt;int&gt;::iterator</span></span><br><span class="line"><span class="keyword">auto</span> it2 = cv.<span class="built_in">begin</span>();  <span class="comment">//it1的类型是vector&lt;int&gt;::const_iterator</span></span><br></pre></td></tr></table></figure>

<p>26.C++11中增加了cbegin()和cend()它们始终返回const_iterator类型，不管对象是不是const。</p>
<p>26.迭代器举例：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;iterator&gt;</span></span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line">    <span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">num</span><span class="params">(<span class="number">10</span>)</span></span>;  <span class="comment">//声明含有10个int元素的vector对象。</span></span><br><span class="line">    <span class="keyword">for</span> (vector&lt;<span class="type">int</span>&gt;::iterator ite = num.<span class="built_in">begin</span>(); ite != num.<span class="built_in">end</span>(); ++ite)      <span class="comment">//使用迭代器将num容器中的元素全部置为1</span></span><br><span class="line">    &#123;</span><br><span class="line">        *ite = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (vector&lt;<span class="type">int</span>&gt;::iterator ite = num.<span class="built_in">begin</span>(); ite != num.<span class="built_in">end</span>(); ++ite)</span><br><span class="line">        cout &lt;&lt; *ite &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">    cout &lt;&lt; endl;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>27.任何改变vector长度的操作都会使已存在的迭代器失效，例如在调用push_back之后，就不能再信任之前指向这个vector的迭代器的值了。所以凡是使用了迭代器的循环体，都不要向迭代器所属的容器添加元素。  </p>
<p>28.vector迭代器支持与指针类似的与常量相加、相减以及指向同一个vector的两个迭代器相减的操作，但不能相加，就像两个指针相加的未定义的一样，同时支持两个迭代器的比较，比较的是它们的位置。</p>
<p>29.string和vector都定义了带符号的difference_type类型，该类型是一个带符号的整型数，可正可负。两个迭代器相减的结果就是difference_type类型。</p>
<p>29.bitset是一种用于处理二进制位的类模板，定义时必须指定其长度值。初始化方式为：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">bitset&lt;n&gt; b;  <span class="comment">//b有n位，每位都为0</span></span><br><span class="line"><span class="function">bitset&lt;n&gt; <span class="title">b</span><span class="params">(u)</span></span>;  <span class="comment">//b是unsigned long 型u的一个副本，用u从低位向高位对b赋值，u不够时高位填充0,多余时舍掉</span></span><br><span class="line"><span class="function">bitset&lt;32&gt; <span class="title">bitvec1</span><span class="params">(<span class="number">0xffff</span>)</span></span>;    <span class="comment">//bitvec为0-15为1,16-31为0，当然这里可以放10进制，也会被自动转为2进制。</span></span><br><span class="line"><span class="function">bitset&lt;n&gt; <span class="title">b</span><span class="params">(s)</span></span>;  <span class="comment">//b是string对象s中含有的位串的副本 ,其中string直接表示为位模式。</span></span><br><span class="line"><span class="function">string <span class="title">strval</span><span class="params">(<span class="string">&quot;1100&quot;</span>)</span></span>;  <span class="comment">//注意这里只能有0和1组成。</span></span><br><span class="line"><span class="function">bitset&lt;32&gt; <span class="title">bitvec2</span><span class="params">(strval)</span></span>; <span class="comment">//bitvec2第2和3位置1,其余位都是0.注意此处不能直接放一个字符串字面值</span></span><br><span class="line"><span class="function">bitset&lt;n&gt; <span class="title">b</span><span class="params">(s, pos, n)</span></span>;  <span class="comment">//b是s中从位置pos开始的n个位的副本</span></span><br></pre></td></tr></table></figure>

<p>30.bitset对象有多种操作能够方便的处理位，参考bitset的reference。也可以使用下标操作符读写某个位。</p>
<p>31.bitset对象返回的数值类型为cstddef头文件中的size_t类型，该类型为与机器相关的unsigned类型。eg:size_t sz = bitvec.size();</p>
<p>32.函数体外定义的数组会被自动初始化为0,函数体内定义的数组不会自动初始化。数组元素为类类型时，不管在哪里定义都会自动调用默认构造函数进行初始化，所以string定义的变量不管在哪里都默认为空字符串，如果没有默认构造函数则必须显示初始化。数组大小必须要在编译时已经，非const的变量只有在运行时才赋值，所以不能使用它作为数组长度。在没有明显性能影响的情况下，能使用vector的地方尽量不要使用数组。使用字符串初始化的字符数组会在数组结尾自动添加’\0’作为结束符。注意数组不能像vector那样直接赋值以及使用另一个数组对其初始化。数组下标类型为<code>size_t</code></p>
<h1 id="指针"><a href="#指针" class="headerlink" title="指针"></a>指针</h1><p>33.指针进行初始化或赋值只能使用以下四种类型的值：1.0值常量表达式，只能是编译时可以获得的0值整型const对象或字面值常量0。2.类型匹配的对象的地址。3.另一对象之后的下一地址。4.同类型的另一个有效指针。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> val;</span><br><span class="line"><span class="type">int</span> zero = <span class="number">0</span>;</span><br><span class="line"><span class="type">const</span> <span class="type">int</span> c_ival = <span class="number">0</span>;</span><br><span class="line"><span class="type">int</span> *pi = ival;    <span class="comment">//ERROR,pi只能指向地址，eg:int *pi = &amp;ival;</span></span><br><span class="line">pi = zero;    <span class="comment">//ERROR，zero为int型变量，只有在运行时才能获取其值</span></span><br><span class="line">pi = c_ival;    <span class="comment">//OK，const的变量在编译时已经确定其值。</span></span><br><span class="line">pi = <span class="number">0</span>;    <span class="comment">//OK，0值字面值常量 ，也可以使用cstdlib头文件中的NULL，int *pi = NULL &lt;=&gt; 0值</span></span><br></pre></td></tr></table></figure>

<p>34.空指针的三种定义方法：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> *p1 = <span class="literal">nullptr</span>;  <span class="comment">//C++11才支持，等价于int *p1 = 0;</span></span><br><span class="line"><span class="type">int</span> *p2 = <span class="number">0</span>;</span><br><span class="line"><span class="comment">//首选include cstdlib头文件</span></span><br><span class="line"><span class="type">int</span> *p3 = <span class="literal">NULL</span>;</span><br></pre></td></tr></table></figure>

<p>34.<code>void *</code> 指针。</p>
<p>35.引用与指针的区别：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> iva1 = <span class="number">1024</span>, iva2 = <span class="number">2048</span>;</span><br><span class="line"><span class="type">int</span> *p1 = &amp;iva1, *p2 = &amp;iva2;</span><br><span class="line"><span class="type">int</span> &amp;r1= ival, &amp;r2= iva2;</span><br><span class="line">p1 = p2;  <span class="comment">//p1指向P2</span></span><br><span class="line">r1= r2;  <span class="comment">//将iva2的值赋给iva1</span></span><br></pre></td></tr></table></figure>

<p>36.两个指针相减返回的数据类型为ptrdiff_t，其也在cstddef中定义，size_t是unsigned类型，而ptrdiff_t则是signed类型。</p>
<h2 id="数组与指针"><a href="#数组与指针" class="headerlink" title="数组与指针"></a>数组与指针</h2><p>1.数组名是数组元素的首地址，即&amp;a[0] == a; 使用下标访问数组时，实际上是使用下标访问指针。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> ia[] = &#123;<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>&#125;;</span><br><span class="line"><span class="type">int</span> i = ia[<span class="number">2</span>]; <span class="comment">//等价于i = *(ia + 2);</span></span><br><span class="line"><span class="type">int</span> *p = &amp;ia[<span class="number">2</span>];</span><br><span class="line"><span class="type">int</span> j = p[<span class="number">-2</span>];  <span class="comment">//等价于j = *(p-2) &lt;=&gt; j = *(&amp;ia[2]-2) = 0;</span></span><br></pre></td></tr></table></figure>
<p>2.在数组与指针混合应用时应采用从数组的名字开始由内向外的方式进行解释  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> *ptr[<span class="number">10</span>];  <span class="comment">//ptr是含有10个指向int型数据的指针的数组  </span></span><br><span class="line"><span class="type">int</span> &amp;ref[<span class="number">10</span>]; <span class="comment">//错误，引用不是对象，所以不存在存放引用的数组</span></span><br><span class="line"><span class="built_in">int</span> (*parray)[<span class="number">10</span>] = &amp;arr; <span class="comment">//parray是一个指向含有10个整数数组的指针</span></span><br><span class="line"><span class="built_in">int</span> (&amp;refarr)[<span class="number">10</span>] = arr; <span class="comment">//refarr是一个引用含有10整数数组的引用  </span></span><br><span class="line"><span class="type">int</span> *(&amp;refparr)[<span class="number">10</span>] = ptr; <span class="comment">//refparr是一个引用含有10个int指针的数组的引用  </span></span><br></pre></td></tr></table></figure>

<p>38.指针相当于数组的迭代器。可以定义指向数组最后一个元素的下一个位置的指针，该指针只能用于比较，不能访问。eg:</p>
<p>39.以下定义数组的方法是非法的，因为数组长度必须是常量表达式。  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">unsigned</span> buff_size = <span class="number">1024</span>;</span><br><span class="line"><span class="type">int</span> arr[buff_size];</span><br></pre></td></tr></table></figure>
<p>33.使用指针访问数组，C++11在头文件iterator中定义了两个函数begin()和end()用于返回指向数组的首元素和尾元素的下一个位置的指针。用法为将数组作为其参数传递。  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//非C++11的方式</span></span><br><span class="line"><span class="type">const</span> <span class="type">size_t</span> arr_sz = <span class="number">5</span>;</span><br><span class="line"><span class="type">int</span> int_arr[arr_sz] = &#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> *pbegin = int_arr, *pend=int_arr+arr_sz; pbegin != pend; ++pbegin)</span><br><span class="line">    cout &lt;&lt; *pbegin &lt;&lt; <span class="string">&#x27; &#x27;</span>;  <span class="comment">//单引号还是双引号在些处一样，单引号表示字符，双引号表示一个字符串,以`\0`结束。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//C++11的方式</span></span><br><span class="line"><span class="type">int</span> *pbeg = <span class="built_in">begin</span>(int_arr), *pend = <span class="built_in">end</span>(int_arr);</span><br><span class="line"><span class="keyword">while</span> (pbeg != pend) </span><br><span class="line">    cout &lt;&lt; pbeg++ &lt;&lt; <span class="string">&#x27; &#x27;</span>;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>39.const和指针：<br>指向const对象的指针：<code>const double *cptr;</code>不需要对其初始化，因为const修饰的是<code>*cptr</code>，它是一个解引用变量，而cptr是一个指向const对象的指针，其本身不是const变量，只是它指向的对象是个const的变量，不能通过它去修改所指向的值，但可以将其指向其他变量。当然此处的cptr可以指向一个非const变量。</p>
<p>const指针：<code>double *const cptr = &amp;a</code>定义了一个<code>const</code>指针cptr，定义时必须初始化。<br>因为const修饰的是cptr而不是*cptr,所以不能修改cptr的指向，cptr只能指向变量a，但可以通过cptr修改a的值，例如:<code>*cptr = 3.14;</code>  </p>
<p>1.指向const对象的const指针：<code>const double *const cptr = &amp;pi;</code>定义时必须初始化，且pi必须是const对象。既不能修改cptr的指向，也不能通过cptr修改其所指向的值。</p>
<p>2.typedef与指针一起使用时的一个例子能更好的理解const的修饰作用：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> string *pstring;</span><br><span class="line"><span class="type">const</span> pstring cstr; </span><br><span class="line"><span class="comment">//cstr的类型为一个指向string类型的const指针。因为pstring是一个指针，它相当于由typedef定义的string *类型，typedef是别名，编译时不会简单的替换，而const修饰的是个指针，所以cstr是个const指针。而define是在预编译时进行简单替换。</span></span><br></pre></td></tr></table></figure>

<p>39.C++11中新增加了通过using来定义类型的别名，eg: <code>using SI = Sales_item;</code>这样SI就是Sales_item的别名，其作用就是把等号左侧的名字规定成等号右侧类型的别名。  </p>
<p>40.当使用非const对象初始化const对象的引用时，系统会自动将非const对象转换为const对象。但不能使用const对象对非const对象的引用初始化。eg:   </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="type">const</span> <span class="type">int</span> *p = &amp;a; <span class="comment">//OK</span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> b = <span class="number">2</span>;</span><br><span class="line"><span class="type">int</span> *p2 = &amp;b; <span class="comment">//Error</span></span><br></pre></td></tr></table></figure>
<p>41.C++11支持constexpr变量，该类型的变量由编译器来验证变量的值是否为一个常量表达式，声明为constexpr的变量一定是一个常量，而且必须用常量表达式初始化，但初始始化时也可以使用constexpr函数作为初始值。  </p>
<p>42.C++11引入了类型指示符decltype，它的作用是选择并返回操作数的数据类型。eg: <code>decltype(f()) sum = x;</code>其中sum的类型就是函数f的返回类型。<br>decltype((variable))的结果永远是引用，而decltype(variable)结果只有当variable本身就是一个引用时才是引用。  </p>
<p>42.动态数组：C++中的new和delete实现了C语言中malloc和free相同的功能。</p>
<p>定义动态数组时只需要指定类型和数组长度，不必为数组对象命名，可以直接初始化为默认值，或者不进行初始化，new表达式返回指向新分配数组的第一个元素指针：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">size_t</span> n = <span class="built_in">get_size</span>();</span><br><span class="line"><span class="type">int</span> *pia = <span class="keyword">new</span> <span class="type">int</span>[n]();<span class="comment">//初始化为int.</span></span><br></pre></td></tr></table></figure>
<p>使用之后需要使用delete语句显式释放分配的动态空间：<code>delete [] pia;</code><br>eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">const</span> <span class="type">char</span> *err = <span class="string">&quot;Error: afunction declaration must specify a function return type!&quot;</span>;</span><br><span class="line"><span class="type">int</span> dimension = <span class="built_in">strlen</span>(err) + <span class="number">1</span>;</span><br><span class="line"><span class="type">char</span> *errMsg = <span class="keyword">new</span> <span class="type">char</span>[dimension];</span><br><span class="line"><span class="built_in">strncpy</span>(errMsg, err, dimesion);</span><br><span class="line"><span class="keyword">delete</span> [] errMsg; <span class="comment">//一定要记得创建时就把释放定后，以免忘记释放</span></span><br></pre></td></tr></table></figure>

<p>43.可以使用数组直接初始化vector对象，但必须给出数组的两个位置指针，如果需要用整个数组初始化，则第二个指针必须是指向数组最后一个元素的下一位置的地址。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">const</span> <span class="type">size_t</span> arr_size = <span class="number">5</span>;</span><br><span class="line"><span class="type">int</span> int_arr[arr_size] = &#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;;</span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">ivec</span><span class="params">(int_arr, int_arr + arr_size)</span></span>;<span class="comment">//使用整个数组。</span></span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">ivec</span><span class="params">(begin(int_arr), end(int_arr))</span></span>;<span class="comment">//使用整个数组。需要C++11支持</span></span><br></pre></td></tr></table></figure>

<h2 id="多维数组与指针"><a href="#多维数组与指针" class="headerlink" title="多维数组与指针"></a>多维数组与指针</h2><p>1.C++中的多维数组指的是数组的数组，不存在真正意义上的多维数组。例如int a[3][4]意思是含有3个int型元素的数组a中，每个元素都是含有4个int型整数的数组。  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> a[] = &#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;;</span><br><span class="line"><span class="type">int</span> b = <span class="number">4</span>;</span><br><span class="line"><span class="type">int</span> *ip[<span class="number">4</span>];  <span class="comment">//指向int类型的指针数组，也就是这个数组里面含有4个指针，每个指针都指向int型数据。</span></span><br><span class="line">ip[<span class="number">1</span>] = &amp;b;  <span class="comment">//将b的地址存放在ip[1]。</span></span><br><span class="line"><span class="built_in">int</span> (*ap)[<span class="number">4</span>]; <span class="comment">//指向4个int型元素的数组指针。  相当于指向地址的指针。</span></span><br><span class="line">ap = &amp;a;  <span class="comment">//让ap指向数组首地址的的地址。</span></span><br><span class="line">cout &lt;&lt; (*ap)[<span class="number">1</span>];  <span class="comment">//输出数组a的第2个值，等价于*(*ap + 1) &lt;=&gt; a[1] &lt;=&gt; *(a + 1)</span></span><br></pre></td></tr></table></figure>

<p>2.多维数组中的引用定义：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> ia[<span class="number">2</span>][<span class="number">3</span>] = &#123;<span class="number">0</span>&#125;;</span><br><span class="line"><span class="built_in">int</span> (&amp;row)[<span class="number">3</span>] = ia[<span class="number">1</span>];  <span class="comment">//定义一个引用row，将它绑定到ia的第二个含有3个元素的数组上</span></span><br></pre></td></tr></table></figure>

<p>3.多维数组中使用range for循环  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> ia[<span class="number">2</span>][<span class="number">3</span>];</span><br><span class="line"><span class="type">size_t</span> cnt = <span class="number">0</span>;</span><br><span class="line"><span class="comment">//此处必须使用引用，一方面是为了修改遍历的值，另一方面防止使用auto时row被自动转换成指针，因为ia是数组</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">auto</span> &amp;row : ia) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">auto</span> &amp;col : row) &#123;</span><br><span class="line">        col = cnt;</span><br><span class="line">        ++cnt;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//外层循环依然要使用引用，防止使用auto时row被自动转换成指针，因为ia是数组。为了避免修改数组，所以使用const</span></span><br><span class="line"><span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;row : ia) &#123;</span><br><span class="line"><span class="comment">//内层循环col即指向row中的每一个元素，因为C++中的多维数组就是数组的数组，row中存放的就是int类型</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">auto</span> col : row) &#123;</span><br><span class="line">        cout  &lt;&lt; col &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.C++11中使用using简化多维数组中指针的使用  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> int_arr = <span class="type">int</span>[<span class="number">3</span>];  <span class="comment">//声明int[3]的别名</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="type">int</span> int_arr[<span class="number">4</span>];  <span class="comment">//等价的typedef声明</span></span><br><span class="line"><span class="comment">//prow指向外层数组  </span></span><br><span class="line"><span class="keyword">for</span> (int_arr *prow = ia; prow != ia + <span class="number">2</span>; ++prow) &#123;</span><br><span class="line"><span class="comment">//*prow即内层数组，pcol指向内层数组的第一个元素，也就是每一行的开头</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> *pcol = *prow; pcol != *prow + <span class="number">3</span>; ++pcol) &#123;</span><br><span class="line">        cout  &lt;&lt; *pcol &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>45.通过指针遍历字符串：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">char</span> *cp = <span class="string">&quot;Hello world&quot;</span>;</span><br><span class="line"><span class="keyword">while</span>(cp &amp;&amp; *cp);  <span class="comment">//表示当cp为非空指针并且cp指向的字符不为空字符null(&#x27;\0&#x27;)时执行循环体。</span></span><br></pre></td></tr></table></figure>
<p>46.C++为在点操作符中使用的解引用操作定义了一个同义词：箭头操作符(-&gt;)。eg:<code>(*p).foo; &lt;=&gt; p-&gt;foo;</code></p>
<p>47.一个帮助理解指针、引用、auto、for range的例子：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> ia[<span class="number">3</span>][<span class="number">4</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">size_t</span> row = <span class="number">0</span>; row &lt; <span class="number">3</span>; ++row) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">size_t</span> col = <span class="number">0</span>; col &lt; <span class="number">4</span>; ++col) &#123;</span><br><span class="line">            ia[row][col] = col + row * <span class="number">4</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//使用C++11中的using来简化定义指向数组的指针</span></span><br><span class="line">    <span class="keyword">using</span> int_arr = <span class="type">int</span>[<span class="number">4</span>];</span><br><span class="line">    <span class="comment">//for (const int_arr &amp;row : ia) &#123;  //类型别名控制外部循环</span></span><br><span class="line">    <span class="comment">//使用引用输出</span></span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;Reference&quot;</span> &lt;&lt; endl;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">const</span> <span class="built_in">int</span> (&amp;row)[<span class="number">4</span>] : ia) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">const</span> <span class="type">int</span> col : row) &#123;</span><br><span class="line">            cout &lt;&lt; col &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl &lt;&lt; <span class="string">&quot;Subscript&quot;</span> &lt;&lt; endl;</span><br><span class="line">    <span class="comment">//使用下标输出</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">size_t</span> row = <span class="number">0</span>; row &lt; <span class="number">3</span>; ++row) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">size_t</span> col = <span class="number">0</span>; col &lt; <span class="number">4</span>; ++col) &#123;</span><br><span class="line">            cout &lt;&lt; ia[row][col] &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl &lt;&lt; <span class="string">&quot;Pointer&quot;</span> &lt;&lt; endl;</span><br><span class="line">    <span class="comment">//使用指针输出</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">const</span> int_arr *row = ia; row != ia + <span class="number">3</span>; ++row) &#123;  <span class="comment">//使用类型别名，row是一个指向含有4个int型元素的指针，ia中含有3个int *型的元素，每个元素又含有4个int的整型</span></span><br><span class="line">   <span class="comment">// for (const int (*row)[4] = ia; row != ia + 3; ++row) &#123;</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">const</span> <span class="type">int</span> *col = *row; col != *row + <span class="number">4</span>; ++col) &#123;</span><br><span class="line">            cout &lt;&lt; *col &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl &lt;&lt; <span class="string">&quot;auto&quot;</span> &lt;&lt; endl;</span><br><span class="line">    <span class="comment">//使用auto</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;row : ia) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">auto</span> col : row) &#123;</span><br><span class="line">            cout &lt;&lt; col &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="表达式和语句"><a href="#表达式和语句" class="headerlink" title="表达式和语句"></a>表达式和语句</h1><h2 id="sizeof"><a href="#sizeof" class="headerlink" title="sizeof"></a>sizeof</h2><p>47.sizeof操作符返回的是编译时常量</p>
<p>48.动态创建的对象初始化时如果不进行直接初始化，对于内置类型或者没有默认构造函数的类型不会自动进行自动初始化。而有默认构造函数的类都会自动调用默认构造函数进行初始化。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> *pi = <span class="keyword">new</span> <span class="type">int</span>;    <span class="comment">//不会自动初始化</span></span><br><span class="line"><span class="type">int</span> *pi = <span class="keyword">new</span> <span class="built_in">int</span>();  <span class="comment">//自动初始化为0</span></span><br></pre></td></tr></table></figure>

<p>48.<code>i != j &lt; k;</code> is equivalent to <code>i != (j &lt; k);</code></p>
<p>49.sizeof运算符作用的结果，部分的依赖于它的作用的类型：  </p>
<ul>
<li>对char或者类型为char的表达式执行sizeof运算，结果为1  </li>
<li>对引用类型执行sizeof运算得到被引用对象所占空间大小  </li>
<li>对指针执行sizeof运算返回指针本身所占空间的大小  </li>
<li>对解引用执行sizeof运算，返回指针所指向的对象所占的空间大小，指针不需要有效  </li>
<li>对数组执行sizeof运算返回整个数组所占空间的大小，相当对使用sizeof对数组中的每个元素运算，并将运算结果求和，注意sizeof作用于数组时，不会将数组转换为指针。   </li>
<li>对string对象或vector对象执行sizeof运算只返回该类型固定部分的大小，不会计算对象中的元素占用了多少空间。也就是说通常对一个vector或string对象执行sizeof运算得不到其占用的总空间大小。例如在我的64位win7操作系统上，<code>vector&lt;int&gt; ivec(1000); cout &lt;&lt; sizeof ivec;</code>输出为24。  </li>
<li>对一个没有声明任何成员变量与成员函数的类名执行sizeof，返回结果为1。因为为了区分该类的不同对象，编译器会在编译时插入一个char，所以结果为1。</li>
</ul>
<h2 id="强制类型转换"><a href="#强制类型转换" class="headerlink" title="强制类型转换"></a>强制类型转换</h2><p>49.C++风格强制类型转换操作符：static_cast、dynamic_cast、const_cast、reinterpret_cast。使用方式为:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">cast-<span class="built_in">name</span>&lt;type&gt;(expression)。</span><br><span class="line"><span class="built_in">const_cast</span>&lt;<span class="type">char</span> *&gt;(pc_str);<span class="comment">//转换掉表达式的const性质。</span></span><br><span class="line"><span class="type">double</span> d = <span class="number">2.0</span>;</span><br><span class="line"><span class="built_in">static_cast</span>&lt;<span class="type">char</span>&gt;(d);  <span class="comment">//将d强制转换为char类型，所有编译器隐式执行的转换都可以通过static_cast显式完成。</span></span><br><span class="line"><span class="built_in">static_cast</span>&lt;type *&gt;(pointer);  <span class="comment">//可以强制将存放在void *中的指针值强制转换为原来的指针类型。</span></span><br></pre></td></tr></table></figure>
<p>应该尽量避免使用强制类型转换。<br>dynamic_cast支持运行时类型识别  </p>
<p>50.static_cast可用于找回存在于void*指针中的值：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> *p = &amp;d;</span><br><span class="line"><span class="type">double</span> *dp = <span class="built_in">static_cast</span>&lt;<span class="type">double</span>*&gt;(p);</span><br></pre></td></tr></table></figure>

<p>50.switch求解的表达式可以非常复杂，也可以直接定义并初始化一个变量。eg:<code>switch(int ival = get_response())</code></p>
<p>51.C++中switch语句中的case之句可以放在一行。eg: <code>case &#39;a&#39;: case &#39;e&#39; : case &#39;i&#39; : case &#39;o&#39;:</code></p>
<p>52.C++中pair类型的用法：pair类型包含在std命名空间下，是一种结构模板类型，它可以同时存储两个类型不同的值。是std::tuple类型的一种只含有两个元素的特例。它含有两个属性，分别是first表示第一个元素值，second表示第二个元素值。使用方法如下：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">pair&lt;string, <span class="type">double</span>&gt; <span class="title">book1</span><span class="params">(<span class="string">&quot;The old man and The sea&quot;</span>, <span class="number">99.99</span>)</span></span>;</span><br><span class="line">pair&lt;string, <span class="type">double</span>&gt; book2;</span><br><span class="line">book2.first = <span class="string">&quot;Harry porter&quot;</span>;</span><br><span class="line">book2.second = <span class="number">88.88</span>;</span><br><span class="line">cout &lt;&lt; book1.first &lt;&lt; <span class="string">&quot;: &quot;</span> &lt;&lt; book1.second &lt;&lt; endl;</span><br><span class="line">cout &lt;&lt; book2.first &lt;&lt; <span class="string">&quot;: &quot;</span> &lt;&lt; book2.second &lt;&lt; endl;</span><br></pre></td></tr></table></figure>

<h2 id="异常"><a href="#异常" class="headerlink" title="异常"></a>异常</h2><p>51.C++的异常：throw表达式抛出异常，try…catch…处理异常。<br>标准异常(4个)：</p>
<ul>
<li>exception头文件定义了最常见的异常类，它的类名是exception。这个类只通知异常的产生，但不会提供更多的信息。  </li>
<li>stdexcept头文件定义了几种常见的异常类。 </li>
<li>new头文件定义了bad_alloc异常类型，提供因无法分配内存而由new抛出的异常。  </li>
<li>type_info头文件定义了bad_cast异常类型。  </li>
</ul>
<p>52.runtime_error异常抛出时必须初始化，示例：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (item1.<span class="built_in">isbn</span>() != item2.<span class="built_in">isbn</span>())</span><br><span class="line">   <span class="keyword">throw</span> <span class="built_in">runtime_error</span>(<span class="string">&quot;Data must refer to same ISBN&quot;</span>);</span><br><span class="line">cout &lt;&lt; item1 + item2 &lt;&lt; endl;</span><br></pre></td></tr></table></figure>

<p>53.try语句块示例：<br>runtime_error类的成员函数what()返回初始化对象时所用的string对象副本，throw语句应在try块中。  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//输入两个整数，输出其相除的结果</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdexcept&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> num1, num2; cout &lt;&lt; <span class="string">&quot;Enter two number: &quot;</span> &lt;&lt; endl, cin &gt;&gt; num1 &gt;&gt; num2;) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (num2 == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="built_in">runtime_error</span>(<span class="string">&quot;Zero is error!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            cout &lt;&lt; num1 &lt;&lt; <span class="string">&quot; / &quot;</span> &lt;&lt; num2 &lt;&lt; <span class="string">&quot; = &quot;</span> &lt;&lt; <span class="built_in">static_cast</span>&lt;<span class="type">double</span>&gt;(num1) / num2 &lt;&lt; endl;</span><br><span class="line">        &#125; <span class="built_in">catch</span> (runtime_error err) &#123;</span><br><span class="line">            cout &lt;&lt; err.<span class="built_in">what</span>()  &lt;&lt; endl &lt;&lt; <span class="string">&quot;Enter \&quot;y\&quot; to continue or \&quot;n\&quot; to end&quot;</span> &lt;&lt; endl;</span><br><span class="line">            <span class="type">char</span> ch;</span><br><span class="line">            cin &gt;&gt; ch;</span><br><span class="line">            <span class="keyword">if</span> (!cin || ch != <span class="string">&#x27;y&#x27;</span>)</span><br><span class="line">              <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h1><p>1.函数在调用前必须声明，定义可以在调用之后，跟C语言一样。</p>
<p>2.计算阶乘的函数  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">fact</span><span class="params">(<span class="type">int</span> i)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"><span class="comment">//注意这里对于0的处理非常合适啊</span></span><br><span class="line">    <span class="keyword">return</span> i &gt; <span class="number">1</span> ? i * <span class="built_in">fact</span>(i - <span class="number">1</span>) : <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3.含有函数声明的头文件应该被包含到定义函数的源文件中。  </p>
<p>52.使用C++中的引用形参比直接使用C类型的指针进行实参访问更安全和自然。引用相当于原变量的一个别名，所以可以直接修改原变量的值。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">swap</span><span class="params">(<span class="type">int</span> &amp;v1, <span class="type">int</span> &amp;v2)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="type">int</span> tmp = v1;</span><br><span class="line">   v1 = v2;</span><br><span class="line">   v2 = tmp;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>53.能用const引用的地方，多用const引用，利用const引用可以避免函数传递时的参数复制。即对于不需要修改变量的函数形参使用引用时应该增加const修饰。  </p>
<p>54.const修饰的string引用参数可以直接接受字面值字符串。  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">find1</span><span class="params">(<span class="type">const</span> string &amp;str)</span></span>;  </span><br><span class="line"><span class="built_in">find1</span>(<span class="string">&quot;Hello&quot;</span>);    <span class="comment">//OK</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">find2</span><span class="params">(string &amp;str)</span></span>;</span><br><span class="line"><span class="built_in">find2</span>(<span class="string">&quot;Hello&quot;</span>);  <span class="comment">//ERROR,type error</span></span><br></pre></td></tr></table></figure>
<p>55.可以通过给函数传递数组首指针begin(arr)和尾指针end(arr)的方式来限定数组的大小，并遍历数组。  </p>
<p>56.<code>int &amp;arr[10]</code>是引用的数组，而<code>int (&amp;arr)[10]</code>却是数组的引用。即声明一个引用，该引用绑定到某个数组。  </p>
<p>57.向函数传递多维数组时，第二维的维度不能省略。<code>int *matrix[10]</code>定义10个指针构成的数组。<code>int (*matrix)[10]</code>定义指向含有10个整数的数组的指针。  </p>
<p>58.C++的main函数传递参数时，定义方法为<code>int main(int argc, char *argv[])</code>或者<code>int main(int argc, char **argv)</code>其中第二个数组中存放的是C风格字符串的指针，所以后一种形式中的argv指向<code>char*</code>。当实参传递给main函数之后，argv的第一个元素指向程序的名字或者一个空字符串，接下来的元素依次为命令行提供的实参，最后一个指针之后的元素值保存为0。eg:<code>prog -d -o ofile data0</code>中argc为5，argv元素分别为”prog”,”-d”,”-o”,”ofile”,”data0”,0。</p>
<p>59.C++11可以使用initializer_list类型的形参来实现多个不同数量相同类型的参数传递。initializer_list是一种标准库类型，用于表示某种特定类型的值的数组。</p>
<p>60.没有返回值的return语句只能用在返回类型是void的函数中，可以用于提前结束程序的运行。返回void的函数，函数在执行到最后一句时会隐式地执行return语句。</p>
<p>61.C++11中可以返回花括号包围的值的列表。类似于其他返回结果，此处的列表也用来对表示函数返回的临时量进行初始化。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">vector&lt;string&gt; <span class="title">process</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (expected.<span class="built_in">empty</span>()) </span><br><span class="line">      <span class="keyword">return</span> &#123;&#125;;</span><br><span class="line">   <span class="keyword">else</span> <span class="keyword">if</span> (expected == actual)</span><br><span class="line">      <span class="keyword">return</span> &#123;<span class="string">&quot;functionx&quot;</span>, <span class="string">&quot;okay&quot;</span>&#125;;</span><br><span class="line">   <span class="keyword">else</span> </span><br><span class="line">      <span class="keyword">return</span> &#123;<span class="string">&quot;abc&quot;</span>, <span class="string">&quot;edu&quot;</span>, actual&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>47.主函数main如果结尾没有返回值，当程序达到了main函数结尾处而且没有return语句，编译器将隐式地插入一条的返回0的return语句。为了使返回值与机器无关，cstdlib头文件中定义了两个预处理变量表达程序执行成功或者失败。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (<span class="literal">true</span>)</span><br><span class="line">      <span class="keyword">return</span> EXIT_FAILURE;</span><br><span class="line">   <span class="keyword">else</span></span><br><span class="line">      <span class="keyword">return</span> EXIT_SUCCESS;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>59.声明一个返回数组指针的函数，形式为: <code>Type (*function(parameter_list))[dimesion]</code>。其中Type是元素的类型，dimension表示数组的大小。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">int</span> (*<span class="built_in">func</span>(<span class="type">int</span> i))[<span class="number">10</span>];</span><br></pre></td></tr></table></figure>
<ul>
<li><code>func(int i)</code> 表示调用func函数时需要一个int类型的实参。  </li>
<li><code>(*func(int i))</code> 意味着我们可以对函数调用的结果执行解引用操作。  </li>
<li><code>(*func(int i))[10]</code> 表示解引用func的调用将得到一个大小是10的数组。  </li>
<li><code>int (*func(int i))[10]</code> 表示数组中的元素是int类型。  </li>
</ul>
<p>60.C++11可以通过尾置返回类型(trailing return type)来简化上述声明。声明方式为<code>auto func(int i) -&gt; int(*)[10];</code>。  </p>
<p>61.编写一个函数声明，该函数返回数组的引用并且该数组包含10个string对象：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">string</span> (&amp;<span class="built_in">func</span>(<span class="built_in">string</span> (&amp;strarr)[<span class="number">10</span>]))[<span class="number">10</span>];</span><br><span class="line"><span class="keyword">using</span> ArrT = string[<span class="number">10</span>];</span><br><span class="line"><span class="function">ArrT <span class="title">func1</span><span class="params">(ArrT&amp; arr)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">auto</span> <span class="title">func2</span><span class="params">(ArrT&amp; arr)</span> -&gt; <span class="title">string</span><span class="params">(&amp;)</span>[10]</span>;</span><br><span class="line">string arrS[<span class="number">10</span>];</span><br><span class="line"><span class="keyword">decltype</span>(arrS)&amp; <span class="built_in">func3</span>(ArrT&amp; arr);</span><br></pre></td></tr></table></figure>

<p>62.C++中一旦某个形参被赋予了默认值，它后面的所有形参都必须有默认值。通常应尽量让不怎么使用默认值的形参出现在前面，而让那些经常使用默认值的形参出现在后面。    </p>
<p>55.标准库都在命名空间std下，例如vector,string,iterator</p>
<p>56.函数中不应该传递vector等容器类形参，可以通过向函数传递对应容器对象的迭代器来访问容器元素。</p>
<p>57.内联函数会在调用点处内联地展开，内联函数通常应该是比较短小的函数，最好定义在头文件中，方便修改和调用。eg  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">inline</span> <span class="type">const</span> string &amp;<span class="title">shorterString</span><span class="params">(<span class="type">const</span> string &amp;s1, <span class="type">const</span> string &amp;s2)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> s1.<span class="built_in">size</span>() &lt; s2.<span class="built_in">size</span>() ? s1:s2 &lt;&lt; endl;;</span><br><span class="line">&#125;</span><br><span class="line">cout &lt;&lt; <span class="built_in">shorterString</span>(s1, s2) &lt;&lt; endl;  <span class="comment">//该调用在编译时将展开为</span></span><br><span class="line">cout &lt;&lt; (s1.<span class="built_in">size</span>() &lt; s2.<span class="built_in">size</span>() ? s1: s2) &lt;&lt; endl;</span><br></pre></td></tr></table></figure>
<p>63.C++11中新增加了constexpr函数(constexpr function)，是指能用于常量表达式的函数，定义constexpr函数的方法与其他函数类似，但要求函数的返回类型及所有形参的类型都是字面值类型，而且函数体中必须有且只有一条return语句，eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">constexpr</span> <span class="type">int</span> <span class="title">new_sz</span><span class="params">()</span> </span>&#123;<span class="keyword">return</span> <span class="number">42</span>;&#125;</span><br><span class="line"><span class="keyword">constexpr</span> <span class="type">int</span> foo = <span class="built_in">new_sz</span>();  <span class="comment">//foo是一个常量表达式，将可以做为数组大小。  </span></span><br></pre></td></tr></table></figure>
<p>为了能在编译过程中随时展开，constexpr函数被隐式指定为内联函数。  </p>
<p>63.和其他函数一样，内联函数和constexpr函数可以在程序中定义多次，所以为了保证定义完全一致，内联函数和constexpr函数通常定义在头文件中。  </p>
<h2 id="C-调试帮助头文件cassert"><a href="#C-调试帮助头文件cassert" class="headerlink" title="C++调试帮助头文件cassert"></a>C++调试帮助头文件cassert</h2><p>64.C++中帮助调式的两个关键字assert(预处理宏)和NDEBUG(预处理变量):  </p>
<ul>
<li><p><code>assert</code>定义在头文件<code>cassert</code>中，用法为<code>assert(expr);</code>，该语句会首先对expr求值，如果表达式为假(即0),assert输出信息并终止程序的执行，如果表达式为真(即非0),assert什么也不做。 assert宏常用于检查“不能发生”的条件。例如一个对输入文本操作的程序可能要求所有给定单词的长度都大于某个阈值，因此，可以这样定义<code>assert(word.size() &gt; threshold);</code>  </p>
</li>
<li><p><code>NDEBUG</code>的作用是限制assert的行为,即assert的行为依赖于NDEBUG的预处理变量的状态，如果定义了NDEBUG，则assert什么也不做，默认状态下没有定义NDEBUG，此时assert将执行运行时检查。可以使用一个<code>#define</code>  语句定义NDEBUG，从而关闭调试状态，如<code>#define NDEBUG</code>，很多编译器也提供一个命令行选项用于定义预处理变量：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CC -D NDEBUG main.c</span><br></pre></td></tr></table></figure>
<p>该命令等价于在main.c文件的开始写一行<code>#define NDEBUG</code>  </p>
</li>
</ul>
<p>65.除了将NDEBUG用于assert外，也可以使用NDEBUG编写自己的条件调试代码。如果NDEBUG未定义，则执行#ifndef和#endif之间的代码，如果定义了NDEBUG，这些代码将被忽略掉。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">print</span><span class="params">(<span class="type">const</span> <span class="type">int</span> ia[], <span class="type">size_t</span> size)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"><span class="meta">#<span class="keyword">ifndef</span> NDEBUG</span></span><br><span class="line">   cerr &lt;&lt; __func__ &lt;&lt; <span class="string">&quot;: array size is &quot;</span>  &lt;&lt; size &lt;&lt; endl; <span class="comment">//__func__是编译器定义的一个局部静态变量，用于存放函数的名字 </span></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>67.编译器定义的可用于调试的名字有：  </p>
<ul>
<li><code>__func__</code>  存放当前调试的函数的名字，它是const char的一个静态数组。  </li>
<li><code>__FILE__</code>  存放文件名的字符串字面值。 </li>
<li><code>__LINE__</code>  存放当前行号的整型字面值。  </li>
<li><code>__TIME__</code>  存放文件编译时间的字符串字面值。  </li>
<li><code>__DATE__</code>  存放文件编译日期的字符串字面值。  </li>
</ul>
<p>68.调试举例：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;cassert&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> NDEBUG</span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">print</span><span class="params">(vector&lt;<span class="type">int</span>&gt; &amp;vec)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"><span class="meta">#<span class="keyword">ifndef</span> NDEBUG</span></span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;vector size: &quot;</span>  &lt;&lt; vec.<span class="built_in">size</span>() &lt;&lt; endl;</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line">    <span class="keyword">if</span> (!vec.<span class="built_in">empty</span>()) &#123;</span><br><span class="line">        <span class="type">int</span> temp = vec.<span class="built_in">back</span>();</span><br><span class="line">        vec.<span class="built_in">pop_back</span>();</span><br><span class="line">        <span class="built_in">print</span>(vec);</span><br><span class="line">        cout &lt;&lt; temp &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    vector&lt;<span class="type">int</span>&gt; veci;</span><br><span class="line">    <span class="keyword">for</span> (vector&lt;<span class="type">int</span>&gt;::size_type i = <span class="number">0</span>; i &lt; <span class="number">10</span>; ++i) &#123;</span><br><span class="line">        veci.<span class="built_in">push_back</span>(i + <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">print</span>(veci);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>70.实参赋给形参时有可能会出现类型转换。  </p>
<p>64.出现在相同作用域中的两个函数，如果具有相同的名字而形参表不同，则称其为重载函数。局部声明的函数将屏蔽全局声明的函数而不是重载，重载函数必须作用域相同。调用重载函数时尽量避免使用强制类型转换，如果一定要使用强制类型转换，则说明重载函数设计不合理。  </p>
<h2 id="函数指针"><a href="#函数指针" class="headerlink" title="函数指针"></a>函数指针</h2><p>65.指向函数的指针定义： bool (<em>pf) (const string &amp;, const string &amp;);  //定义了一个指向含有两个const string &amp;类型形参，返回bool类型的函数指针pf。使用typedef可以简化定义，typedef bool (</em>tdpf) (const string &amp;, const string &amp;);</p>
<p>66.函数指针只能通过同类型的函数或函数指针或0值常量表达式进行初始化或赋值。函数指针初始化时，直接引用函数名等效于在函数名上应用取地址操作符：<code>tdpf pf1 = getnum;</code> &lt;=&gt; <code>tdpf pf1 = &amp;getnum;</code></p>
<p>67.通过函数指针调用函数时不需要对其解引用。eg: pf(“Hello”, “world”);</p>
<p>68.当指向函数的指针作为形参时可能使用如下两种方式编写：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">useBigger</span><span class="params">(<span class="type">const</span> string &amp;, <span class="type">const</span> string &amp;, <span class="type">bool</span> (<span class="type">const</span> string &amp;, <span class="type">const</span> string &amp;))</span></span>;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">useBigger</span><span class="params">(<span class="type">const</span> string &amp;, <span class="type">const</span> string &amp;, <span class="type">bool</span> (*)(<span class="type">const</span> string &amp;, <span class="type">const</span> string &amp;))</span></span>;   <span class="comment">//就像普通类型的定义类似，不需要指名函数名。</span></span><br></pre></td></tr></table></figure>

<p>69.返回指向函数的指针，可能从函数名开始由里向外分析。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">int</span>  (*<span class="built_in">ff</span>(<span class="type">int</span>))(<span class="type">int</span> *, <span class="type">int</span>);  <span class="comment">//它表示ff声明为一个函数，它带有一个int型的形参，并返回`int (*)(int *, int);`，它是一个指向函数的指针，该函数返回int型并带有两个分别为`int *`和`int`的形参。其等价的typedef定义为：</span></span><br><span class="line"><span class="function"><span class="keyword">typedef</span> <span class="title">int</span> <span class="params">(*PF)</span><span class="params">(<span class="type">int</span> *, <span class="type">int</span>)</span></span>;</span><br><span class="line"><span class="function">PF <span class="title">ff</span><span class="params">(<span class="type">int</span>)</span></span>;</span><br></pre></td></tr></table></figure>

<p>70.函数无法返回函数，只能返回指向函数的指针。而当形参为指向函数的指针时，具有函数类型的对应的实参会被自动转换为指向相应函数类型的指针。eg:   </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">typedef</span> <span class="type">int</span> <span class="title">func</span><span class="params">(<span class="type">int</span> *, <span class="type">int</span>)</span></span>;  <span class="comment">//func为函数类型</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">f1</span><span class="params">(func)</span></span>;  <span class="comment">//OK,f1含有一个函数类型的形参</span></span><br><span class="line"><span class="function">func <span class="title">f2</span><span class="params">(<span class="type">int</span>)</span></span>;  <span class="comment">//ERROR，f2返回的是个函数</span></span><br><span class="line"><span class="function">func *<span class="title">f3</span><span class="params">(<span class="type">int</span>)</span></span>;  <span class="comment">//OK，f3返回类型为指向函数的指针。</span></span><br></pre></td></tr></table></figure>

<p>71.C++允许使用函数指针指向重载的函数。定义该指针时其类型必须与重载函数精确匹配。</p>
<h1 id="类"><a href="#类" class="headerlink" title="类"></a>类</h1><p>1.类的声明和定义可以在一起，即声明一个类类型时，同时定义它的成员。也可以暂时只声明而不定义。eg: <code>class Sales_data;</code>。这种声明被称作前面声明（forward declaration），在它声明之后定义之前是一个不完全类型（incomplete type）。不完全类型只能在非常有限的情况下使用：可以定义指向这种类型的指针或引用，也可以声明（但不能定义）以不完全类型作为参数或者返回类型的函数。  </p>
<p>58.类的所有成员必须在定义类的花括号中声明，成员函数的定义可以放在类的定义内定义，也可以放在类的定义外定义。放在类的定义内定义的成员函数会被编译器隐式地当作内联(inline)函数。当成员函数在类外进行定义时，记得命名空间，在类外定义时也可以使用inline进行修饰，通常应该加上inline以便于阅读。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">double</span> <span class="title">Sales_item::avg_price</span><span class="params">()</span> <span class="type">const</span> </span>&#123;&#125;</span><br></pre></td></tr></table></figure>

<p>59.每个类成员函数都隐含的包含一个形参this,在调用成员函数时，形参this初始化为调用函数的对象的地址。在成员函数中，不必显示的使用this指针来访问被调用函数所属对象的成员。对这个类的成员的任何没有前缀的引用，都被假定为通过指针this实现的引用,此规则只是针对对象的成员函数的调用，在定义成员函数时必须使用this。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">inline</span> <span class="type">void</span> <span class="title">Sales_item::add_price</span><span class="params">(<span class="type">double</span> price)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">this</span>-&gt;price = price;  <span class="comment">//其中this-&gt;price为类成员属性price，必须使用this-&gt;price</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>60.如果在成员函数名后面,花括号前面加上修鉓符const，则this将成为指向调用对象的const的指针,该成员函数称为常量成员函数。可以有效保护对象不被成员函数修改。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//该函数将无法修改this.isbn及this所指对象的常量成员。</span></span><br><span class="line"><span class="function"><span class="type">bool</span> <span class="title">same_isbn</span><span class="params">(<span class="type">const</span> Sales_item &amp;rhs)</span> <span class="type">const</span></span></span><br><span class="line"><span class="function"></span>&#123;<span class="keyword">return</span> isbn == rhs.isbn;&#125;  <span class="comment">//等价于&#123;this-&gt;isbn == rhs.isbn;&#125;</span></span><br></pre></td></tr></table></figure>

<p>61.函数可以直接返回整个对象，或者返回一个对象的引用，也可以返回this对象。 eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Sales_item&amp; <span class="title">Sales_item::combine</span><span class="params">(<span class="type">const</span> Sales_item &amp;rhs)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="comment">//combine this and rhs</span></span><br><span class="line">   <span class="keyword">return</span> *<span class="keyword">this</span>; <span class="comment">//</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>62.IO类属于不能被拷贝的类型，所以函数在传递IO类时需要以引用的方式传递。  </p>
<h2 id="构造函数"><a href="#构造函数" class="headerlink" title="构造函数"></a>构造函数</h2><p>61.构造函数与类同名，且没有返回类型。每个类可以有多个构造函数，每个构造函数的形参表必须不同。构造函数应该放在public部分，用于初始化对象。</p>
<p>62.当类中没有构造函数时，编译器会自动生成默认构造函数。但不能依赖于默认构造函数，通常应该为类定义默认构造函数，原因为：  </p>
<ul>
<li>当我们定义了其他构造函数时，编译器将不会再生成默认构造函数，除非再定义一个默认构造函数，否则类将没有默认构造函数。  </li>
<li>如果类包含内置类型或者复合类型的成员，只有当这些成员都有类内初始值时，这个类才能合适地使用默认构造函数。  </li>
<li>有些情况下编译器也无法为某些类合成默认构造函数。例如，如果类中包含一个其他类类型的成员且这个成员的类型没有默认构造函数时。  </li>
</ul>
<p>63.C++11中允许使用 <code>= default</code>的方式来要求编译器生成默认构造函数。eg: <code>Sales_data() = default;</code>  </p>
<p>62.构造函数的定义：”类名(形参表)：构造函数的初始化列表 {函数体}”eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Sales_data</span>(): <span class="built_in">units_sold</span>(<span class="number">0</span>), <span class="built_in">revenue</span>(<span class="number">0.0</span>) &#123;&#125;  <span class="comment">//成员名后面的圆括号中为成员初值</span></span><br></pre></td></tr></table></figure>
<p>构造函数也可以只在类内声明，然后在类外面进行定义，在类外面定义时，必须通过类名指定该构造函数属于哪个类。<br>构造函数的初始化列表可以为空，函数体也可以为空。  </p>
<p>63.类的定义为 class 类名 {}; 记得后面要有个分号。</p>
<p>63.类内的变量的初始值不能使用圆括号初始化。  </p>
<p>5.struct和class的唯一区别是默认访问级别，struct默认访问级别为public，class默认访问级别是private。</p>
<p>6.类中public部分定义的成员在程序的任何部分都可以访问，通常在public部分放置操作，以便在程序的其他部分可以执行这些操作。类中private部分定义的成员只能被作为类的组成部分的代码（以及该类的友元）访问。通常在private部分放置数据，以对对象的内部数据进行隐藏。</p>
<h2 id="友元"><a href="#友元" class="headerlink" title="友元"></a>友元</h2><p>7.类可以通过友元来允许其他类或者函数访问它的非公有成员，方法是在类内部使用关键字friend声明相应的函数。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">friend</span> std::istream &amp;<span class="title">read</span><span class="params">(std::istream&amp;, Sales_data&amp;)</span></span>;</span><br></pre></td></tr></table></figure>
<p>友元的声明只能出现在类定义的内部，但在类内出现的位置不限，友元不是类的成员，所以也不受它所在区域访问控制级别的约束。一般，最好在类定义开始或结束前的位置集中声明友元。  </p>
<p>8.由于友元的声明仅仅指定了访问的权限，并非一个通常意义上的函数声明。所以如果我们希望类的用户能够调用某个友元函数，那么我们就必须在友元声明之外再专门对函数进行一次声明。  </p>
<p>9.可以通过在类中定义某种类型的别名来隐藏类的具体实现，在类中定义的类型名字同样存在访问限制，可以是public或者private中的一种。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Screen</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">   <span class="keyword">typedef</span> std::string::size_type pos; <span class="comment">//等价于using pos = std::string::size_type;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">   pos cursor = <span class="number">0</span>;</span><br><span class="line">   pos height = <span class="number">0</span>, width = <span class="number">0</span>;</span><br><span class="line">   std::string contents;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>10.类的成员函数也可以被重载。  </p>
<p>11.可以通过关键字mutable将类的数据成员声明为可变数据成员(mutable data member)，可变数据成员永远不会是const，即使它是const对象的成员，const成员函数依然可以改变它的值。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Screen</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">   <span class="function"><span class="type">void</span> <span class="title">some_member</span><span class="params">()</span> <span class="type">const</span></span>;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">   <span class="keyword">mutable</span> <span class="type">size_t</span> access_ctr;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Screen::some_member</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   ++access_ctr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>8.类内初始值必须使用=的初始化形式或者花括号括起来的直接初始化形式。  </p>
<p>9.成员函数返回<code>*this</code>时，如果该函数需要修改对象的成员，应让其返回对象的引用，这样即可以避免只能改变对象的临时副本，又能避免数据拷贝。  </p>
<p>10.一个const成员函数如果以引用的形式返回*this，那么它的返回类型将是常量引用。  </p>
<p>11.即使两个类的成员列表完全一致，它们也是不同的类型。  </p>
<p>12.默认初始化类的方式：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">以下两个声明等价</span><br><span class="line">Sales_data item1;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Sales_data</span> item1;  <span class="comment">//C语言中通常使用这种方式  </span></span><br></pre></td></tr></table></figure>

<p>13.类可以把其他的类定义成友元，也可以把其他类的成员函数定义成友元，友元函数能定义在类的内部，这样的函数是隐式内联的。友元关系不存在传递性，每个类负责控制自己的友元类或友元函数。eg:    </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//A是B的友元类，所以A的成员函数将可以访问B中包括非公有成员在内的所有成员。  </span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">A</span> &#123;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">do</span><span class="params">(B&amp;)</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> &#123;</span><br><span class="line"><span class="keyword">friend</span> <span class="keyword">class</span> <span class="title class_">A</span>;</span><br><span class="line"><span class="comment">//指定类A中的某个成员函数成为B的友元。  </span></span><br><span class="line"><span class="function">free <span class="type">void</span> <span class="title">A::do</span><span class="params">(B&amp;)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">A::<span class="built_in">do</span>(B&amp; b) &#123;<span class="keyword">return</span> *<span class="keyword">this</span>&#125;</span><br></pre></td></tr></table></figure>
<p>要想令某个成员函数作为友元，必须仔细组织程序的结构以满足声明和定义的彼此依赖关系，必须按照如下方式设计程序：  </p>
<ul>
<li>首先定义A类，其中声明do函数，但此时不能定义，在do使用B的成员之前必须先声明B。  </li>
<li>接下来定义B，包括对于do的友元声明。  </li>
<li>最后定义do函数的实际内容，此时它才可以使用B的成员。</li>
</ul>
<p>14.类和非成员函数的声明不是必须在它们的友元声明之前，此时隐匿地假定该名字在当前作用域是可见的。即使在类的内部定义友元时定义该函数，也必须在类的外部提供相应的声明从而使得函数可见。eg:    </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">X</span> &#123;</span><br><span class="line">   <span class="function"><span class="keyword">friend</span> <span class="type">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123; &#125; <span class="comment">//友元可以定义在类的内部</span></span><br><span class="line">   <span class="built_in">X</span>() &#123;<span class="built_in">f</span>();&#125;  <span class="comment">//错误：f还没有被声明</span></span><br><span class="line">   <span class="function"><span class="type">void</span> <span class="title">g</span><span class="params">()</span></span>;</span><br><span class="line">   <span class="function"><span class="type">void</span> <span class="title">h</span><span class="params">()</span></span>;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">X::g</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> <span class="built_in">f</span>(); &#125;  <span class="comment">//错误：f还没有被声明</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">f</span><span class="params">()</span></span>;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">X::h</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> <span class="built_in">f</span>(); &#125; <span class="comment">//正确：现在f的声明在作用域中了</span></span><br></pre></td></tr></table></figure>

<p>14.一旦遇到类名，定义的剩余部分就在类的作用域之内了，这里的剩余部分包括参数列表和函数体，也就是此时可以直接使用类的成员，而无需再次指明类名。但类名之前的成员必须通过<code>::</code>来指明其所属类（例如成员函数的返回类型），包括在类中定义的类型别名。  </p>
<p>15.编译器在处理类的定义时分两步：首先编译成员的声明，然后直到类全部可见后才编译函数体。所以定义在类内的成员函数中可以使用在其后定义的成员。而声明中使用的名字，包括返回类型及参数列表则必须在使用前确保可见。    </p>
<p>16.通常内层作用域中可以重新定义外层作用域中的名字，即使该名字已经在内层作用域中使用过，然后在类中，如果成员使用外层作用域中的某个名字，而该名字代表一种类型，则类不能在之后重新定义该名字。  </p>
<p>17.三种情况下类成员必须在默认构造函数中显示初始化：成员是const或者是引用，或者当成员属于某种类类型且该类型没有定义默认构造函数时。  </p>
<p>18.由于构造函数初始化列表的顺序与成员声明的顺序一致，所有最好令构造函数初始值的顺序与成员声明的顺序保持一致。且如果有可能，应尽量避免使用某些成员初始化其他成员，这样就可以不必考虑成员的初始化顺序。  </p>
<p>19.如果一个构造函数为所有参数都提供了默认实参，则它实际上也定义了默认构造函数。  </p>
<p>20.C++11中新增加了委托构造函数。一个委托构造函数使用它所属类的其他构造函数执行它自己的初始化过程，或者说它把它自己的一些职责委托给其他构造函数。委托构造函数的声明也有一个成员初始值的列表和一个函数体，其成员初始值列表只有一个唯一的入口，就是类名本身，类名后面紧跟圆括号括起来的参数列表，参数列表必须与类中的另一个构造函数匹配。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Sales_data</span> &#123;</span><br><span class="line"><span class="keyword">public</span>: </span><br><span class="line"><span class="comment">//非委托构造函数使用对应的实参初始化成员</span></span><br><span class="line">   <span class="built_in">Sales_data</span>(std::string s, <span class="type">unsigned</span> cnt, <span class="type">double</span> price): <span class="built_in">bookNo</span>(s), <span class="built_in">units_sold</span>(cnt), <span class="built_in">revenue</span>(cnt*price) &#123; &#125;</span><br><span class="line"><span class="comment">//下面的构造函数全都委托给另一个构造函数</span></span><br><span class="line">   <span class="built_in">Sales_data</span>(): <span class="built_in">Sales_data</span>(<span class="string">&quot;&quot;</span>, <span class="number">0</span>, <span class="number">0</span>) &#123; &#125;</span><br><span class="line">   <span class="built_in">Sales_data</span>(std::string s): <span class="built_in">Sales_data</span>(s, <span class="number">0</span>, <span class="number">0</span>) &#123; &#125;</span><br><span class="line">   <span class="built_in">Sales_data</span>(std::istream &amp;is): <span class="built_in">Sales_data</span>() &#123; <span class="built_in">read</span>(is, *<span class="keyword">this</span>); &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>21.如果构造函数只接受一个实参，则它实际上定义了将该实参转换为此类类型的隐式转换机制，有时我们把这种构造函数称作转换构造函数，即这种构造函数的参数可以初始隐式的转换为该类的类类型。例如当类A中的某个构造函数只含有一个string类型的实参作为其参数列表时，当调用函数中的参数需要使用A时，则可以使用string直接替代，此时编译器会用给定的string自动创建一个A对象，并将这个（临时）的A对象传递给调用函数，这里的调用函数的参数应该是一个常量引用。编译器只会执行一步类型转换，也就是说当你使用一个字符串字面值直接给这个调用函数时，将无法编译通过，因为它不能被自动转换为string然后再转换为A对象，必须强制将其先转换为string。  </p>
<p>22.可以通过将构造函数声明为explicit以阻止构造函数的隐式转换，这样构造函数A将不能再成为转换构造函数。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span> &#123;</span><br><span class="line">   <span class="keyword">public</span>:</span><br><span class="line">   <span class="function"><span class="keyword">explicit</span> <span class="title">A</span><span class="params">(<span class="type">const</span> std::string &amp;s)</span>: bookNo(s) &#123;</span>&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当构造函数被声明为explicit时，它将只能以直接初始化的形式使用（即圆括号），而不能使用赋值初始化（即通过=号进行的拷贝初始化）  </p>
<p>13.类类型当然也支持显式的强制类型转换，例如：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span> &#123;</span><br><span class="line">   std::string bookNo;</span><br><span class="line">   <span class="keyword">public</span>:</span><br><span class="line">   <span class="built_in">A</span>(std::string s): <span class="built_in">bookNo</span>(s) &#123;&#125;</span><br><span class="line">   <span class="function"><span class="type">void</span> <span class="title">combin</span><span class="params">(A)</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line">A itemA;</span><br><span class="line">itemA.<span class="built_in">combin</span>(<span class="built_in">A</span>(<span class="string">&quot;Hello&quot;</span>));</span><br><span class="line">itemA.<span class="built_in">combin</span>(<span class="built_in">static_cast</span>&lt;A&gt;(<span class="string">&quot;Hello&quot;</span>));</span><br></pre></td></tr></table></figure>

<p>19.聚合类使得用户可以直接访问其成员，并且具体特殊的初始化语法形式。当满足以下条件时，才是聚合类：  </p>
<ul>
<li>所有成员都是public的  </li>
<li>没有定义任何构造函数  </li>
<li>没有类内初始值  </li>
<li>没有基类，也没有virtual函数。<br>这种类在初始化时使用花括号括起来的成员初始值列表进行初始化，初始值的顺序必须与声明的顺序一致。<br>eg:  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Data</span> &#123;</span><br><span class="line">   <span class="type">int</span> ival;</span><br><span class="line">   string s;</span><br><span class="line">&#125;;</span><br><span class="line">Data val = &#123;<span class="number">0</span>, <span class="string">&quot;test&quot;</span>&#125;;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>21.数据成员都是字面值类型的聚合类是字面值常量类。如果一个类不是聚合类，但它符合以下要求，也可以是一个字面值常量类：  </p>
<ul>
<li>数据成员都必须是字面值类型  </li>
<li>类必须至少含有一个constexpr构造函数  </li>
<li>如果一个数据成员含有类内初始值，则内置类型成员的初始值必须是一条常量表达式；或者如果成员属于某种类类型，则初始值必须使用成员自己的constexpr构造函数。  </li>
<li>类必须使用析构函数的默认定义，该成员负责销毁类的对象。  </li>
</ul>
<p>22.通过static声明类的静态成员（可以是数据或者函数），类的静态成员直接与类本身关联，而不是与类的各个对象保持关联。静态成员也可以是public或private，静态数据成员的类型可以是常量、引用、指针、类类型等。类的静态成员被该类的所有对象所共享。静态成员函数不能声明成const的，而且也不能在static函数体内使用this指针。<br>由于非静态成员需要实例化后才会分配内存，而静态成员属于类，一直存在于内存中，所以静态成员不能访问非静态成员。但非静态成员可以访问类的静态成员</p>
<p>21.静态成员函数即可以定义在类的内部也可以定义在类的外部，但定义在类的外部时不能重复static关键字，static关键字只出现在类内部的声明语句中。  </p>
<p>23.使用静态成员的方式：</p>
<ul>
<li>直接使用作用域运算符通过类名来访问静态成员，eg:<code>double r = Account::rate();</code>  </li>
<li>使用类的对象、引用或指针来访问静态成员，eg:  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Account ac1;</span><br><span class="line">Account *ac2 = &amp;ac1;</span><br><span class="line"><span class="comment">//以下两种方式等价</span></span><br><span class="line"><span class="type">double</span> r = ac1.<span class="built_in">rate</span>();</span><br><span class="line"><span class="type">double</span> ac2-&gt;<span class="built_in">rate</span>();</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h1 id="标准IO库"><a href="#标准IO库" class="headerlink" title="标准IO库"></a>标准IO库</h1><ul>
<li>iostream  对流进行读写  从istream和ostream派生而来  含istream和ostream</li>
<li>fstream  读写文件，由iostream派生而来  含ifstream和ofstream</li>
<li>sstream  对string对象进行读写，由iostream派生而来  含istringstream和ostringstream</li>
</ul>
<p>73.标准IO为了对国际字符的支持，有一组带”w”前缀的IO库。如wostream、wistream、wiostream等对应的char类型为wchar_t类型。对应的标准输入输出对象为wcin、wcout，还有wcerr.</p>
<p>74.IO对象不可复制或复制，而只有支持复制的元素类型可以存储在容器类型中，所以IO对象不支持容器。形参或返回类型也不能为流类型，如果需要传递或者返回IO对象，则必须传递或返回指向该对象的指针或引用。</p>
<p>75.标准IO库的条件状态标志，适用于普通流、文件流以及string流。注意，这些只是状态标准，例如s.clear()只是将流的标志重置为有效状态，但并不会清空流的缓冲区。清空缓冲区需要使用cin.sync()。</p>
<p>failbit通常是可以修正，例如需要int却输入了字符串则为s.fail()返回true，此时可能通过s.clear()进行重置流状态为有效。而badbit是系统级的故障，出现这类错误时的流将无法再使用。</p>
<p>76.输出缓冲区的管理。每个IO对象管理一个缓冲区用于存储程序读写的数据。输出缓冲区的内容被刷新的方式有：<br>1).程序正常结束。作为main返回工作的一部分，将清空所有输出缓冲区。<br>2).在一些不确定的时候，缓冲区已经满了，此时缓冲区将会在下一个值写入之前刷新。<br>3).用操纵符显式地刷新缓冲区，例如结束符endl用于输出一个换行符并刷新缓冲区，flush用于刷新流但不在输出中添加任何字符，ends在缓冲区中插入字符null然后再刷新它。<br>4).在每次输出操作执行完成后，用unitbuf操纵符设置流的内部状态，从而清空缓冲区。<br>如果需要刷新所有输出，最好使用unitbuf，它每次执行完写操作后都刷新流：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cout &lt;&lt; unitbuf &lt;&lt; <span class="string">&quot;first&quot;</span> &lt;&lt; <span class="string">&quot; second&quot;</span> &lt;&lt; nounitbuf;</span><br></pre></td></tr></table></figure>
<p>等价于：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cout &lt;&lt; <span class="string">&quot;first&quot;</span> &lt;&lt; flush &lt;&lt; <span class="string">&quot; second&quot;</span> &lt;&lt; flush;</span><br></pre></td></tr></table></figure>
<p>nounitbuf 操纵符将流恢复为使用正常的、由系统管理的缓冲区刷新方式。<br>5).可将输出流与输入流关联(使用tie函数)起来，这样，在读输入流时将刷新其关联的输出缓冲区。<br>当输入流与输出流绑在一起时，任何读输入流的尝试都将首先刷新其输出流关联的缓冲区。标准库将cout与cin绑在一起。eg:<br>cin.tie(&amp;cout);</p>
<p>77.程序在崩溃时不会自动刷新输出缓冲区</p>
<p>78.从标准输入一直读取直到遇到文件结束符，不管读到时是否发生了错误都进入循环，可有效检测错误原因，记得使用逗号。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> (cin &gt;&gt; ival, !cin.<span class="built_in">eof</span>())</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span> (cin.<span class="built_in">bad</span>())    <span class="comment">//检测流是否为不可恢复的的badbit</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="built_in">runtime_error</span>(<span class="string">&quot;IO stream corrupted&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (cin.<span class="built_in">fail</span>())    <span class="comment">//检测流是否为还可以再使用的failbit错误，如果是则重置failbit标志并重新使用该流</span></span><br><span class="line">    &#123;</span><br><span class="line">        cerr &lt;&lt; <span class="string">&quot;bad data, try again&quot;</span>;</span><br><span class="line">        cin.<span class="built_in">clear</span>(istream::failbit);   <span class="comment">//重置流的状态标志，但不会清空输入缓冲区。</span></span><br><span class="line">        cin.<span class="built_in">sync</span>();  <span class="comment">//清空输入缓冲区中的所有内容。</span></span><br><span class="line">        <span class="keyword">continue</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>79.当需要处理多种状态时可以使用按位或操作符在一次调用中生成“两个或更多状态位”。eg：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">is.<span class="built_in">setstate</span>(ifstream::badbit | ifstream::failbit);  <span class="comment">//同时设置badbit和failbit位为真</span></span><br></pre></td></tr></table></figure>

<p>80.cin.clear()重置cin的状态标志为有效，cin.sync()清空输入缓冲区中的内容，cin.ignor()可用于清空输入流中的部分内容。</p>
<h2 id="文件的输入和输出"><a href="#文件的输入和输出" class="headerlink" title="文件的输入和输出"></a>文件的输入和输出</h2><p>fstream头文件定义了三种支持文件IO的类型：</p>
<ul>
<li>ifstream，由istream派生，提供读文件的功能。</li>
<li>ofstream，由ostream派生，提供写文件的功能。</li>
<li>fstream，由iostream派生，提供读写同一个文件的功能。<br>eg:  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ifstream <span class="title">infile</span><span class="params">(ifile.c_str())</span></span>;  <span class="comment">//定义并初始化输入文件流infile，并将其与将要读取的文件ifile绑定。 &lt;=&gt;`ifstream infile; infile.open(&quot;in&quot;);`//假设文件名为in并在当前文件夹</span></span><br><span class="line"><span class="function">ofstream <span class="title">outfile</span><span class="params">(ofile.c_str())</span></span>;  <span class="comment">//定义并初始化输出文件流outfile，并将其与将要写入的文件ofile绑定。 &lt;=&gt;`ofstream outfile; outfile.open(&quot;out&quot;);`//假设文件名为out并在当前文件夹</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>82.检查文件是否已成功打开<code>if (!infile)</code>。如果要将文件流与新文件重新捆绑必须先将其关闭<code>infile.close();</code></p>
<p>83.关于文件的读写实例：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fstream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"><span class="comment">//    string file = &quot;out.txt&quot;;</span></span><br><span class="line"><span class="comment">//    cin &gt;&gt; file;</span></span><br><span class="line"><span class="comment">//    ofstream outfile(file.c_str());  //定义并打开一个用于写入的文件流outfile，记得转成c风格字符串</span></span><br><span class="line"><span class="comment">//    cin.clear();  //重置输入流标志防止cin有可能出现的错误</span></span><br><span class="line"><span class="comment">//    cin.sync();  //清空输入流缓冲区的内容</span></span><br><span class="line"><span class="comment">//    if (!outfile)  //判断写文件流是否有效</span></span><br><span class="line"><span class="comment">//    &#123;</span></span><br><span class="line"><span class="comment">//        cout &lt;&lt; &quot;Error to open the file &quot; &lt;&lt; file &lt;&lt; endl;</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"><span class="comment">//    else</span></span><br><span class="line"><span class="comment">//    &#123;</span></span><br><span class="line"><span class="comment">//        cout &lt;&lt; &quot;Enter some words:&quot; &lt;&lt; endl;</span></span><br><span class="line"><span class="comment">//        string str;</span></span><br><span class="line"><span class="comment">//        getline(cin, str);  //一次读到一行</span></span><br><span class="line"><span class="comment">//        outfile &lt;&lt; str;  //将str写到文件输出流outfile中</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"><span class="comment">//    outfile.close();  //关闭文件流</span></span><br><span class="line">    string file = <span class="string">&quot;sales_item.h&quot;</span>;</span><br><span class="line">    <span class="function">ifstream <span class="title">infile</span><span class="params">(file.c_str())</span></span>;  <span class="comment">//定义并初始化文件输入流 </span></span><br><span class="line">    <span class="keyword">if</span> (!infile)</span><br><span class="line">    &#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Error to open infile &quot;</span> &lt;&lt; file &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        cout &lt;&lt; file &lt;&lt; <span class="string">&quot;: &quot;</span> &lt;&lt; endl;</span><br><span class="line"><span class="comment">//        string str;</span></span><br><span class="line"><span class="comment">//        getline(infile, str);</span></span><br><span class="line"><span class="comment">//        cout &lt;&lt; str &lt;&lt; endl;</span></span><br><span class="line">        string str;</span><br><span class="line">        vector&lt;string&gt; sales;</span><br><span class="line">        <span class="keyword">while</span> (!infile.<span class="built_in">eof</span>())</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">getline</span>(infile, str);</span><br><span class="line">            sales.<span class="built_in">push_back</span>(str);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (vector&lt;string&gt;::const_iterator ite = sales.<span class="built_in">begin</span>(); ite != sales.<span class="built_in">end</span>(); ++ite)</span><br><span class="line">        &#123;</span><br><span class="line">            cout &lt;&lt; *ite &lt;&lt; endl;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    infile.<span class="built_in">close</span>();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>84.文件的打开模式，注意这些模式指的是文件的模式而不是流的模式。<br>其中out、trunc和app模式只能用于ofstream或者fstream，in模式只能用于ifstream或fstream。所有的文件都可以使用ate或binary模式。<br>eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ofstream <span class="title">outfile</span><span class="params">(<span class="string">&quot;filename&quot;</span>, ofstream::out | ofstream::trunc)</span></span>;  <span class="comment">//使用按位或操作符同时以out和trunc模式打开文件。</span></span><br></pre></td></tr></table></figure>
<p>默认时ifstream流对象关联的文件将以in模式打开，ofstream默认以out模式打开。以out模式打开的文件内容会被清空，效果上等同于同时指定了out和trunc模式。</p>
<p>85.fstream既可以读也可以写它所关联的文件，如何处理它的文件取决于它打开的模式。eg:<br>fstream inout(“filename”, fstream::in | fstream::out);  //同时以输入和输出模式打开文件</p>
<p>86.打开模式的有效组合：</p>
<p>87.打开文件前若未知原文件流的状态，一定记得首先使用in.close();in.clear();重置原来的流。</p>
<h2 id="字符串流"><a href="#字符串流" class="headerlink" title="字符串流"></a>字符串流</h2><p>88.字符串流的操作包含在头文件sstream头文件中。类似于文件流它包含对应的三种类型：istringstream、ostringstream和stringstream。像fstream一样，iostream的操作也都适用于sstream相关对象。</p>
<p>89.stringstream的特定操作strm.str();strm.str(s);  </p>
<p>90.字符串流的用处：<br>1)可以同时对一行以及一行中的单词进行处理。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">string line, word;</span><br><span class="line"><span class="keyword">while</span> (<span class="built_in">getline</span>(cin, line))</span><br><span class="line">&#123;</span><br><span class="line">    <span class="function">istringstream <span class="title">stream</span><span class="params">(line)</span></span>;  <span class="comment">//定义并初始化stringstream对象</span></span><br><span class="line">    <span class="keyword">while</span> (stream &gt;&gt; word)    <span class="comment">//从一行中读取单词</span></span><br><span class="line">    &#123;</span><br><span class="line">        processing;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2)stringstream可用于转换或格式化字符串。eg:<br>将数字转化为字符串：<br>int val1 = 512, val2 = 1024;<br>ostringstream format_message;<br>format_message &lt;&lt; “val1: “ &lt;&lt; val1 &lt;&lt; “\n” &lt;&lt; “val2: “ &lt;&lt; val2 &lt;&lt; “\n”;  //format_message内容将为val1: 512\nval2: 1024</p>
<p>将字符串转化为数字：<br>istringstream input_istring(format_message.str());<br>string dump;<br>input_istring &gt;&gt; dump &gt;&gt; val1 &gt;&gt; dum &gt;&gt; val2;  //非数字将被输入到dump而数字512和1024将分别被输入val1和val2。程序会自动忽略换行符。</p>
<h1 id="顺序容器"><a href="#顺序容器" class="headerlink" title="顺序容器"></a>顺序容器</h1><p>元素在顺序容器中的顺序与其加入容器时的位置相对应。<br>关联容器中元素的位置由元素相关联的关键字值决定。<br>1.顺序容器类型：  </p>
<ul>
<li>vector 相当于可变大小的数组。支持快速随机访问，在尾部之外的位置插入或删除元素可能很慢。  </li>
<li>deque 双端队列。支持快速随机访问。在头尾位置插入/删除速度很快。  </li>
<li>list 双向链表。只支持双向顺序访问。在list中任何位置进行插入或删除操作速度都很快。  </li>
<li>forward_list(C++11) 单向链表。只支持单向顺序访问。在链表任何位置进行插入或删除都很快。  </li>
<li>array(C++11) 固定大小的数组。支持快速随机访问，不能添加或删除元素。  </li>
<li>string 与vector相似的容器，但专门用于保存字符。随机访问快，在尾部插入或删除速度快。<br>除了固定大小的array外，其他容器都提供高效、灵活的内存管理。<br>string和vector的元素保存的连续的内存空间中，所以对其使用下标访问元素速度依然很快，但在中间位置插入元素由于需要移动大量元素，所以会非常慢。<br>list和forward_list可以方便地在任何位置添加或删除元素，速度都会很快，但不支持随机访问。而且与vector、deque和array相比，这两个容器的额外内存开销也很大。<br>deque是一个更为复杂的数据结构，与string和vector类似，其支持随机访问，同样在中间位置添加或删除元素代价可能会很高。但在deque的两端添加或删除元素都很快，可以与list或forward_list添加删除元素的速度相当。<br>与内置的数组相比，C++11新增加的array是一种更安全、更容易使用的数组类型，当然其大小也是固定的。C++11中的forward_list设计的目标是达到与最好的手写单向链表数据结构相当的性能，所以forward_list没有size操作。  </li>
</ul>
<p>2.通常，使用vector是最好的选择，除非你有很好的理由选择其他容器。  </p>
<p>3.每个容器都定义在其相应的头文件中，容器均定义为模板类。  </p>
<p>4.可以定义元素类型为容器的容器，如<code>vector&lt;vector&lt;string&gt;&gt; lines</code>，C++11之前的版本需要在后面两个尖括号之前加一个空格。  </p>
<p>5.每种容器都支持迭代器及对应的操作，其他forward_list的迭代器不支持<code>--</code>运算符。  </p>
<p>6.容器的迭代器所描述的元素范围称为左闭合区间[begin, end)，因为end指向的是容器最后一个元素的下一个位置。  </p>
<p>7.在不需要修改容器元素的情况下记得使用const_iterator迭代器。  </p>
<p>8.每个容器的迭代器也都有其对应的反向迭代器reverse_iterator，反向迭代器++会获取其前一个元素。  </p>
<p>9.容器的索引类型为container<type>::size_type，例如int的vector的索引类型为<code>vector&lt;int&gt;::size_type</code>   </p>
<p>10.<code>begin</code>和<code>end</code>返回的迭代器有多个版本，以r开头的版本返回反向迭代器，以c开头的版本返回const迭代器。例如:    </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">list&lt;string&gt; a;</span><br><span class="line"><span class="keyword">auto</span> it1 = a.<span class="built_in">begin</span>();  <span class="comment">//list&lt;string&gt;::iterator</span></span><br><span class="line"><span class="keyword">auto</span> it2 = a.<span class="built_in">rbegin</span>();  <span class="comment">//list&lt;string&gt;::reverse_iterator</span></span><br><span class="line"><span class="keyword">auto</span> it3 = a.<span class="built_in">cbegin</span>();  <span class="comment">//list&lt;string&gt;::const_iterator</span></span><br><span class="line"><span class="keyword">auto</span> it4 = a.<span class="built_in">crbegin</span>();  <span class="comment">//list&lt;string&gt;::const_reverse_iterator</span></span><br></pre></td></tr></table></figure>
<p>所以当不需要写访问时，应使用cbegin和cend  </p>
<p>11.除了array之外，其他容器的默认构造函数都会创建一个指定类型的空容器，且顺序容器都可以接受指定容器大小和元素初始值的参数。使用方法与vector一样。    </p>
<p>12.与内置数组一样，标准库array的大小也是类型的一部分，当定义一个array时，除了指定元素类型，还要指定容器大小：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">array&lt;<span class="type">int</span>, 42&gt; a1; <span class="comment">//定义一个保存42个int的数组</span></span><br><span class="line">array&lt;<span class="type">int</span>, 10&gt;::size_type i;  <span class="comment">//定义类型为array&lt;int, 10&gt;::size_type的数组下标</span></span><br></pre></td></tr></table></figure>

<p>13.array支持拷贝或对象赋值操作，由于类型必须一样(元素类型和大小都是类型的一部分)：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">array&lt;<span class="type">int</span>, 10&gt; digits = &#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;;</span><br><span class="line">array&lt;<span class="type">int</span>, 10&gt; copy = digits;</span><br></pre></td></tr></table></figure>

<p>14.vector的6种创建和初始化方式及初始值：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">vector&lt;<span class="type">int</span>&gt; vec;    <span class="comment">// 0</span></span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">vec</span><span class="params">(<span class="number">10</span>)</span></span>;    <span class="comment">// 0</span></span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">vec</span><span class="params">(<span class="number">10</span>, <span class="number">1</span>)</span></span>;  <span class="comment">// 1</span></span><br><span class="line">vector&lt;<span class="type">int</span>&gt; vec&#123; <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span> &#125;; <span class="comment">// 1, 2, 3, 4, 5</span></span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">vec</span><span class="params">(other_vec)</span></span>; <span class="comment">// same as other_vec</span></span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">vec</span><span class="params">(other_vec.begin(), other_vec.end())</span></span>; <span class="comment">// same as other_vec</span></span><br></pre></td></tr></table></figure>

<p>15.用于容器的swap和assign函数：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">swap</span>(c1, c2); <span class="comment">//交换c1和c2中的元素。c1和c2必须具有相同的类型</span></span><br><span class="line">c1.<span class="built_in">swap</span>(c2); <span class="comment">//swap通常比从c2向c1拷贝元素快得多  </span></span><br><span class="line"><span class="comment">//assign操作不适用于关联容器和array</span></span><br><span class="line">seq.<span class="built_in">assign</span>(b, e);  <span class="comment">//将seq中的元素替换为迭代器b和e所表示的范围中的元素。迭代器b和e不能指向seq中的元素  </span></span><br><span class="line">seq.<span class="built_in">assign</span>(il);  <span class="comment">//将seq中的元素替换为初始化列表il中的元素</span></span><br><span class="line">seq.<span class="built_in">assign</span>(n, t); <span class="comment">//将seq中的元素替换为n个值为t的元素</span></span><br></pre></td></tr></table></figure>

<p>16.可变大小的容器都有三个与大小相关的操作：size()返回容器中的元素数目；empty()判断容器是否为空；max_size()返回一个大于或等于该类型容器所能容纳的最大元素数的值。  </p>
<p>17.每个容器都支持相等运算符(==和!=)，除了无序关联容器外的所有容器都支持关系运算符（<code>&gt;、&gt;=、&lt;、&lt;=</code>）。</p>
<p>18.顺序容器都有其相应的添加和删除元素的操作（push_back、insert、emplace等），其中emplace系列的成员函数是C++11中引入的，它们执行的操作是构造而不是拷贝元素，所以速度会快一些，因为拷贝元素时会创建一个临时变量。  </p>
<p>19.支持下标访问的容器有string、vector、deque、array，它们同时支持通过at来较安全的访问。下标越界的结果是未定义的，而at访问越界时会抛出out_of_range异常，用法为<code>c.at(n)</code>。   </p>
<p>20.访问元素的成员函数（即front、back、下标和at）返回的都是引用，即可以作为左值使用，如<code>c.front() = 42;</code>  </p>
<p>21.容器操作可能会使迭代器失效，特别是在改变了容器的大小时要特别留意是否在改变容器之后依然使用了改变之前的迭代器。  </p>
<p>22.容器大小管理操作：  </p>
<ul>
<li>shrink_to_fit 只适用于vector、string和deque。  </li>
<li>capacity和reserve只适用于vector和string。  </li>
<li>c.shrink_to_fit()  将capacity()减少为与size()相同大小  </li>
<li>c.reserve(n)  分配至少能容纳n个元素的内存空间<br>reserve并不改变容器中元素的数量，它仅影响vector预先分配多大的内存空间。只有当需要的内存空间超过当前容量时，reserve调用才会改变vector的容量。<br>capacity和size：容器的size是指它已经保存的元素的数目；而capacity则是在不分配新的内存空间的前提下它最多可以保存多少元素。  </li>
</ul>
<p>22.string还支持另外三个构造函数：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//n、len2、pos2都是无符号值</span></span><br><span class="line"><span class="function">string <span class="title">s</span><span class="params">(cp, n)</span></span>; <span class="comment">//s是cp指向的数组中前n个字符的拷贝，此数组至少应该包含n个字符。  </span></span><br><span class="line"><span class="function">string <span class="title">s</span><span class="params">(s2, pos2)</span></span>;  <span class="comment">//s是string s2从下标pos2开始的字符的拷贝，若pos2&gt;s2.size(),构造函数的行为未定义  </span></span><br><span class="line"><span class="function">string <span class="title">s</span><span class="params">(s2, pos2, len2)</span></span>;  <span class="comment">//s是string s2从下标pos2开始len2个字符的拷贝。若pos2&gt;s2.size(),构造函数的行为未定义。不管len2的值是多少，构造函数至多拷贝s2.size()-pos2个字符  </span></span><br></pre></td></tr></table></figure>

<p>22.string有着丰富的成员函数，可以支持修改、查找、搜索、比较、数值转换等功能。  </p>
<h2 id="容器适配器"><a href="#容器适配器" class="headerlink" title="容器适配器"></a>容器适配器</h2><p>1.标准库中有三个顺序容器适配器：stack、queue和priority_queue，stack在stack头文件中，其他两个都在queue头文件中。容器、迭代器和函数都有适配器，容器适配器即一个容器适配器接受一种已有的容器类型，使其行为看起来像一种不同的类型。所有容器适配器都支持empty、size和swap函数。  </p>
<p>2.每个适配器都定义两个构造函数：默认构造函数创建一个空对象，接受一个容器的构造函数拷贝该容器来初始化适配器。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">deque&lt;<span class="type">int</span>&gt; deq;</span><br><span class="line"><span class="function">stack&lt;<span class="type">int</span>&gt; <span class="title">stk</span><span class="params">(deq)</span></span>; <span class="comment">//从deq拷贝元素到stk，假设deq中已经有初始值 </span></span><br><span class="line"><span class="comment">//在vector上实现的string类型的空栈</span></span><br><span class="line">stack&lt;string, vector&lt;string&gt;&gt; str_stk;</span><br><span class="line"><span class="comment">//str_stk2在vector上实现，初始化时保存svec的拷贝</span></span><br><span class="line">stack&lt;string, vector&lt;string&gt;&gt;  <span class="built_in">str_stk2</span>(svec);</span><br></pre></td></tr></table></figure>
<p>默认情况下，stack和queue是基于deque实现的，priority_queue是在vector之上实现的。  </p>
<p>3.所有适配器都要求容器具有添加、删除元素的能力，每一种容器适配器都有其对应的构造容器的限制。  </p>
<p>4.栈适配器stack在标准库头文件stack中，stack默认基于deque实现，也可以在list或者vector之上实现，其支持的其他特有操作：  </p>
<ul>
<li>s.pop()  删除栈顶元素，但不返回该元素值    </li>
<li>s.push(item)  创建一个新元素压入栈顶，该元素通过拷贝或移动item而来  </li>
<li>s.emplace(args)  同上，只是其由args构造  </li>
<li>s.top()  返回栈顶元素，但不将元素弹出栈<br>虽然适配器基于容器，但不能直接使用容器的操作。  </li>
</ul>
<p>5.队列适配器queue和priority_queue定义在queue头文件中，其中queue默认基于deque实现，priority_queue默认基于vector实现，queue也可以用list或vector实现，priority_queue也可以用deque实现。其支持的其他操作：    </p>
<ul>
<li>q.pop()    </li>
<li>q.front()  </li>
<li>q.back()  </li>
<li>q.top()  </li>
<li>q.push(item)  </li>
<li>q.emplace(args)<br>标准库queue使用一种先进先出（first-in，first-out，FIFO）的存储和访问策略。  </li>
</ul>
<h1 id="泛型算法"><a href="#泛型算法" class="headerlink" title="泛型算法"></a>泛型算法</h1><p>由于标准库容器定义的操作集合很小，所以标准库为这些容器定义了一组通用（generic，或称泛型的）算法：它们可以用于不同类型的容器和不同类型的元素。通常这些算法并不直接操作容器，而是遍历由两个迭代器指定的一个元素范围来进行操作。<br>1.大多数算法都定义在头文件algorithm中，头文件numeric中定义了一组数值泛型算法。<br>algorithm所有算法: <a target="_blank" rel="noopener" href="http://www.cplusplus.com/reference/algorithm/">http://www.cplusplus.com/reference/algorithm/</a>  </p>
<p>2.泛型算法本身不会执行容器的操作，它们只会运行于迭代器之上，执行迭代器的操作。所以算法永远不会改变底层容器的大小。算法可能改变容器中保存元素的值，也可能在容器内移动元素，但永远不会直接添加或删除元素。算法可以通过操作标准库定义的一类特殊的迭代器——插入器（inserter）来完成容器添加元素的效果。  </p>
<p>3.除了少数例外，标准库算法都对一个范围内的元素进行操作，我们将此元素范围称为“输入范围”，接受输入范围的算法总是使用前两个参数来表示此范围，两个参数分别是指向要处理的第一个元素和尾元素之后位置的迭代器。   </p>
<p>4.那些只接受一个单一迭代器来表示第二个序列的算法，都假定第二个序列至少与第一个序列一样长。  </p>
<p>5.向目的位置迭代器写入数据的算法假定目的位置足够大，能容纳要写入的元素。注意vector等容器默认声明时如果不指定大小，是不分配初始空间大小的。  </p>
<p>6.插入迭代器可以通过容器算法向容器中赋值，back_inserter是一个定义在头文件iterator中的函数，可以用其生成插入迭代器。back_inserter接受一个指向容器的引用，返回一个与该容器绑定的插入迭代器，当我们通过此迭代器赋值时，赋值运算符会调用push_back将一个具有给定值的元素添加到容器中。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">vector&lt;<span class="type">int</span>&gt; vec;</span><br><span class="line"><span class="keyword">auto</span> it = <span class="built_in">back_inserter</span>(vec);</span><br><span class="line">*it = <span class="number">42</span>; <span class="comment">//向vec中添加一个元素，值为42</span></span><br><span class="line"><span class="built_in">fill_n</span>(vec, <span class="number">10</span>, <span class="number">0</span>); <span class="comment">//错误，fill_n无法向不存在的容器空间中写入数据。</span></span><br><span class="line"><span class="built_in">fill_n</span>(<span class="built_in">back_inserter</span>(vec), <span class="number">10</span>, <span class="number">0</span>); <span class="comment">//添加10个值为0的元素到vec中</span></span><br></pre></td></tr></table></figure>

<p>7.拷贝算法copy接受三个迭代器，前两个指定输入范围，第三个表示目的序列的起始位置，返回目的位置迭代器（递增后）的值。</p>
<p>8.replace算法可以将给定范围内的某个值替换为另一个值。  </p>
<p>9.重排容器元素的算法：sort()接受两个迭代器指定范围按字典序排序；unique()接受两个迭代器指定范围，将输入范围中重复值放在序列的后面，并返回指向不重复区域之后一个位置的迭代器；  </p>
<p>10.sort函数的默认排序是通过<code>&lt;</code>进行比较，可能通过向其传递第三个参数来指定比较方式，函数会对其每一个参数调用第三个参数代指的函数，通常第三个参数被称为谓词，谓词分为一元谓词（unary predicate）和二元谓词（binary predicate）。stable_sort可以维持相等元素的原有顺序。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">bool</span> <span class="title">isShorter</span><span class="params">(<span class="type">const</span> std::string &amp;a, <span class="type">const</span> std::string &amp;b)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="keyword">return</span> a.<span class="built_in">size</span>() &lt; b.<span class="built_in">size</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用方法</span></span><br><span class="line"><span class="built_in">stable_sort</span>(words.<span class="built_in">begin</span>(), words.<span class="built_in">end</span>(), isShorter);</span><br></pre></td></tr></table></figure>

<h2 id="lambda表达式"><a href="#lambda表达式" class="headerlink" title="lambda表达式"></a>lambda表达式</h2><p>C++11新增的lambda表达式相当于未命名的内联函数，可以定义在函数内部。表达式形式如下：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[capture list] (parameter list) -&gt; <span class="keyword">return</span> type &#123;function body&#125;;</span><br></pre></td></tr></table></figure>
<p>其中capture list（捕获列表）是一个lambda所在函数中定义的局部变量的列表（通常为空）；return type、parameter list和function body分别表示返回类型、参数列表和函数体，lambda必须使用尾置返回来指定返回类型。可以忽略参数列表和返回类型，但必须包含捕获列表和函数体。  </p>
<p>1.函数名加小括号即表示调用运算符，如<code>f()</code>。</p>
<p>2.使用lambda表达式的例子：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">stable_sort</span>(words.<span class="built_in">begin</span>(), words.<span class="built_in">end</span>(), [](<span class="type">const</span> string &amp;a, <span class="type">const</span> string &amp;b) &#123;<span class="keyword">return</span> a.<span class="built_in">size</span>() &lt; b.<span class="built_in">size</span>();&#125;);</span><br></pre></td></tr></table></figure>
<p>实现上例的功能，空捕获列表表示此lambda不使用它所在函数中的任何局部变量。一个lambda只有在其捕获列表中捕获一个它所在函数中的局部变量，才能在函数体中使用该变量。但lambda可以直接使用局部static变量和在它所有函数之外声明的名字。    </p>
<p>3.使用for_each函数配合lambda表达式输出容器中的元素，每个元素后面接一个空格。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">for_each(words.<span class="built_in">begin</span>(), words.<span class="built_in">end</span>(), [](<span class="type">const</span> string &amp;s)&#123;cout &lt;&lt; s &lt;&lt; <span class="string">&quot; &quot;</span>;&#125;);</span><br></pre></td></tr></table></figure>

<p>4.当定义一个lambda时，编译器生成一个与lambda对应的新的（未命名的）类类型。  </p>
<p>5.与参数不同，lambda表达式中被捕获的变量的值是在lambda创建时拷贝，而不是调用时拷贝。  </p>
<p>6.可以通过给lambda的捕获列表传递=或&amp;告诉编译器隐匿地采用值捕获方式或引用捕获方式，当然也支持混合使用显示捕获与隐式捕获。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">for_each(words.<span class="built_in">begin</span>(), words.<span class="built_in">end</span>(), [&amp;, c](<span class="type">const</span> string &amp;s) &#123; os &lt;&lt; s &lt;&lt; c;&#125;);</span><br></pre></td></tr></table></figure>
<p>当混合使用隐式捕获与显示捕获时，捕获列表的第一个元素必须是一个&amp;或=，此符号即指定了默认捕获方式为引用或值，且显示捕获的变量必须采用与隐式捕获不同的方式。  </p>
<p>7.默认情况下，对于一个值被拷贝的局部变量，传递给lambda时为只读变量，lambda不会改变其值。可能通过在参数列表首加上关键字mutable来使用lambda可以改变局部变量的值。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">fcn3</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="type">size_t</span> v1 = <span class="number">42</span>;</span><br><span class="line">   <span class="comment">//如果没有mutable，编译将报错，因为v1是只读的</span></span><br><span class="line">   <span class="keyword">auto</span> f = [v1]() <span class="keyword">mutable</span> &#123;<span class="keyword">return</span> ++v1;&#125;;</span><br><span class="line">   v1 = <span class="number">0</span>;</span><br><span class="line">   <span class="keyword">auto</span> j = <span class="built_in">f</span>(); <span class="comment">//j为43</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>8.默认情况下，如果一个lambda体包含return之外的任何语句，则编译器假定此lambda返回void。  </p>
<p>9.当需要手动指定lambda的返回类型时，需要使用尾置返回类型：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//transform算法可以遍历修改序列中的值</span></span><br><span class="line"><span class="built_in">transform</span>(vi.<span class="built_in">begin</span>(), vi.<span class="built_in">end</span>(), vi.<span class="built_in">begin</span>(), [](<span class="type">int</span> i) -&gt; <span class="type">int</span>  &#123;<span class="keyword">if</span> (i &lt; <span class="number">0</span>) <span class="keyword">return</span> -i; <span class="keyword">else</span> <span class="keyword">return</span> i;&#125;);</span><br></pre></td></tr></table></figure>

<p>10.标准库头文件functional中的bind函数可以将函数生成为一个新的可调用对象来“适应”原对象的参数列表。  </p>
<h2 id="iterator"><a href="#iterator" class="headerlink" title="iterator"></a>iterator</h2><p>11.标准库在头文件iterator中还定义了以下几种迭代器：  </p>
<ul>
<li>插入迭代器（insert iterator）：用于与一个容器绑定并向容器中插入元素。  <ul>
<li>back_inserter  </li>
<li>front_inserter  </li>
<li>inserter  </li>
</ul>
</li>
<li>流迭代器（stream iterator）：这些迭代器被绑定到输入或输出流上，可用来遍历所关联的IO流。通过使用流迭代器，我们可以用泛型算法从流对象读取数据以及向其写入数据。    <ul>
<li>istream_iterator 读取输入流。    </li>
<li>ostream_iterator 向一个流写入数据。   </li>
</ul>
</li>
<li>反向迭代器（reverse iterator）：即在容器中从尾元素向首元素反向移动的迭代器。  </li>
<li>移动迭代器（move iterator）：这种迭代器不拷贝其中的元素，而是移动它们。  </li>
</ul>
<p>1.插入迭代器用法：<code>std::unique_copy(lstr.begin(), lstr.end(), back_inserter(l_unique));</code>  </p>
<p>2.istream_iterator用法：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">istream_iterator&lt;T&gt; <span class="title">in</span><span class="params">(is)</span></span>;  <span class="comment">//in从流is读取类型为T的值</span></span><br><span class="line">istream_iterator&lt;T&gt; end;  <span class="comment">//读取类型为T的值的istream_iterator迭代器，表示尾后位置。  </span></span><br><span class="line"><span class="comment">//下面从标准输入读取数据存入vector</span></span><br><span class="line"><span class="function">istream_iterator&lt;<span class="type">int</span>&gt; <span class="title">in_ter</span><span class="params">(cin)</span></span>;  <span class="comment">//从cin读取int</span></span><br><span class="line">istream_iterator&lt;<span class="type">int</span>&gt; eof;  <span class="comment">//istream尾后迭代器</span></span><br><span class="line"><span class="keyword">while</span> (in_ter != eof)  <span class="comment">//当有数据可供读取时</span></span><br><span class="line">   vec.<span class="built_in">push_back</span>(*in_ter++);</span><br><span class="line"><span class="comment">//等价于</span></span><br><span class="line"><span class="function">istream_iterator&lt;<span class="type">int</span>&gt; <span class="title">in_ter</span><span class="params">(cin)</span>, eof</span>; <span class="comment">//从cin读取int</span></span><br><span class="line"><span class="function">vector&lt;<span class="type">int</span>&gt; <span class="title">vec</span><span class="params">(in_ter, eof)</span></span>; <span class="comment">//从迭代器范围构造vec</span></span><br></pre></td></tr></table></figure>

<p>2.ostream_iterator用法：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ostream_iterator&lt;T&gt; <span class="title">out</span><span class="params">(os)</span></span>;  <span class="comment">//out将类型为T的值写到输出流os中</span></span><br><span class="line"><span class="function">ostream_iterator&lt;T&gt; <span class="title">out</span><span class="params">(os, d)</span></span>;  <span class="comment">//out将类型为T的值写到输出流os中，每个值后面都输出一个d。d指向一个空字符结尾的字符数组，例如字符串字面值。</span></span><br><span class="line"><span class="comment">//以下利用ostream_iterator输出vector的元素</span></span><br><span class="line"><span class="function">ostream_iterator&lt;<span class="type">int</span>&gt; <span class="title">out_iter</span><span class="params">(cout, <span class="string">&quot; &quot;</span>)</span></span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">auto</span> e : vec)</span><br><span class="line">   *out_iter++ = e; <span class="comment">//等价于out_iter = e;</span></span><br><span class="line">cout &lt;&lt; endl;</span><br><span class="line"><span class="comment">//以上等价于使用copy的如下实现</span></span><br><span class="line"><span class="built_in">copy</span>(vec.<span class="built_in">begin</span>(), vec.<span class="built_in">end</span>(), out_iter);</span><br><span class="line">cout &lt;&lt; endl;</span><br></pre></td></tr></table></figure>

<p>3.iostream的迭代器举例：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//实现功能为使用istream_iterator从文件读取string到vector中，然后使用ostream_iterator将vector中的元素输出到标准输出cout中</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iterator&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fstream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="comment">//定义文件流</span></span><br><span class="line">    <span class="function">std::ifstream <span class="title">in</span><span class="params">(<span class="string">&quot;test.cpp&quot;</span>)</span></span>;</span><br><span class="line">    <span class="comment">//使用文件流创建istream_iterator及文件结尾eof</span></span><br><span class="line">    <span class="function">std::istream_iterator&lt;std::string&gt; <span class="title">in_ter</span><span class="params">(in)</span>, eof</span>;</span><br><span class="line">   <span class="comment">//使用文件迭代器创建一个存放string的vector</span></span><br><span class="line">    <span class="function">std::vector&lt;std::string&gt; <span class="title">vecstr</span><span class="params">(in_ter, eof)</span></span>;</span><br><span class="line">    <span class="comment">//创建标准输出迭代器</span></span><br><span class="line">    <span class="function">std::ostream_iterator&lt;std::string&gt; <span class="title">out</span><span class="params">(std::cout, <span class="string">&quot; &quot;</span>)</span></span>;</span><br><span class="line">    <span class="comment">//使用copy函数将vector中的内容拷贝的含有标准输出的迭代器</span></span><br><span class="line">    std::<span class="built_in">copy</span>(vecstr.<span class="built_in">begin</span>(), vecstr.<span class="built_in">end</span>(), out);</span><br><span class="line">    std::cout &lt;&lt; std::endl;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>5.除了forward_list之外，其他容器都支持反向迭代器。</p>
<p>6.每个算法都会对它的每个迭代器参数指明须提供哪类迭代器。按算法要求可分为以下5类迭代器：  </p>
<ul>
<li>输入迭代器  只读，不写；单遍扫描，只能递增；find和accumulate要求输入迭代器，istream_iterator是一种输入迭代器。  </li>
<li>输出迭代器  只写，不读；单遍扫描，只能递增；ostream_iterator类型是输出迭代器    </li>
<li>前向迭代器  可读写；多遍扫描，只能递增；forward_list上的迭代器是前向迭代器    </li>
<li>双向迭代器  可读写；多遍扫描，可递增递减；除了forward_list之外，其他标准库都提供双向迭代器    </li>
<li>随机访问迭代器  可读写；多遍扫描，支持全部迭代器运算；array、deque、string和vector的迭代器都是随机访问迭代器       </li>
</ul>
<p>7.算法命名规范：  </p>
<ul>
<li>_if版本的算法接受一个谓词代替元素值，适用于lambda表达式。eg:    <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">find</span>(beg, end, val);  <span class="comment">//查找输入范围中val第一次出现的位置</span></span><br><span class="line"><span class="built_in">find_if</span>(beg, end, pred); <span class="comment">//查找第一个令pred为真的元素  </span></span><br></pre></td></tr></table></figure></li>
<li>_copy版本的算法会将元素拷贝到目的位置eg:  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">reverse</span>(beg, end);  <span class="comment">//反转元素</span></span><br><span class="line"><span class="built_in">reverse_copy</span>(beg, end, dest);  <span class="comment">//反转元素并拷贝到dest</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>8.list和forward_list定义了它们自己的sort, merge, remove, reverse和unique算法。  </p>
<h1 id="关联容器"><a href="#关联容器" class="headerlink" title="关联容器"></a>关联容器</h1><p>1.关联容器支持高效的关键字查找和访问。两个主要的关联容器类型是map和set。map使用关键字进行索引，set中每个元素只包含一个关键字，它支持高效的关键字查询操作——检查一个给定的关键字是否在set中。  </p>
<p>2.对于关联容器来说，第一个元素就相当于数组下标，第二个元素是对应下标下存储的值。    </p>
<p>2.标准库中一共定义了8个关联容器其中map和multimap定义在头文件map中；set和multiset定义在头文件set中；无序容器则定义在头文件unordered_map和unordered_set中。  </p>
<ul>
<li>按关键字有序保存元素的容器:  <ul>
<li>map   关联数组；保存关键字-值对</li>
<li>set   关键字即值，即只保存关键字的容器  </li>
<li>multimap  关键字可重复出现的map  </li>
<li>multiset  关键字可重复出现的set  </li>
</ul>
</li>
<li>无序集合:  <ul>
<li>unordered_map  用哈希函数组织的map  </li>
<li>unordered_set  用哈希函数组织的set  </li>
<li>unordered_multimap  用哈希函数组织的map；关键字可以重复出现  </li>
<li>unordered_multiset  用哈希函数组织的set；关键字可以重复出现  </li>
</ul>
</li>
</ul>
<p>3.关联容器使用举例：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * testmap.cpp</span></span><br><span class="line"><span class="comment"> * 从test.cpp文件中读取单词，并统计单词出现的次数，不统计排除列表中的单词，能够将大小写单词，以及结尾有符号的单词识别为同一个单词，例如&quot;Expam&quot;，&quot;expam.&quot;，&quot;expam,&quot;为同一个单词</span></span><br><span class="line"><span class="comment"> * Copyright (C) 2015  &lt;@BLUEYI-PC&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Distributed under terms of the MIT license.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;map&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;set&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iterator&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fstream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;cctype&gt;</span></span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">//声明文件流并初始化</span></span><br><span class="line">    <span class="function">std::ifstream <span class="title">in</span><span class="params">(<span class="string">&quot;test.cpp&quot;</span>)</span></span>;</span><br><span class="line">    <span class="comment">//使用文件流初始化流迭代器</span></span><br><span class="line">    <span class="function">std::istream_iterator&lt;std::string&gt; <span class="title">in_ite</span><span class="params">(in)</span>, eof</span>;</span><br><span class="line">    <span class="comment">//声明map，用于存放单词与其个数</span></span><br><span class="line">    std::map&lt;std::string, <span class="type">size_t</span>&gt; word_count;</span><br><span class="line">    <span class="comment">//声明set，存放排除列表</span></span><br><span class="line">    std::set&lt;std::string&gt; exclude = &#123;<span class="string">&quot;&#123;&quot;</span>, <span class="string">&quot;&#125;&quot;</span>, <span class="string">&quot;the&quot;</span>, <span class="string">&quot;and&quot;</span>&#125;;</span><br><span class="line">    std::string word;</span><br><span class="line">    <span class="keyword">while</span> (in_ite != eof) &#123;</span><br><span class="line">        word = *in_ite;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">auto</span> &amp;ch : word) ch = std::<span class="built_in">tolower</span>(ch);</span><br><span class="line">        word.<span class="built_in">erase</span>(std::<span class="built_in">remove_if</span>(word.<span class="built_in">begin</span>(), word.<span class="built_in">end</span>(), ispunct), word.<span class="built_in">end</span>());</span><br><span class="line">        <span class="keyword">if</span> (exclude.<span class="built_in">find</span>(word) == exclude.<span class="built_in">end</span>()) &#123;</span><br><span class="line">            ++word_count[word];</span><br><span class="line">        &#125;</span><br><span class="line">        in_ite++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">const</span> <span class="keyword">auto</span> &amp;w : word_count) &#123;</span><br><span class="line">        std::cout &lt;&lt; w.first &lt;&lt; <span class="string">&quot; occurs &quot;</span> &lt;&lt; w.second &lt;&lt; ((w.second &gt; <span class="number">1</span>) ? <span class="string">&quot; times&quot;</span> : <span class="string">&quot; time&quot;</span>) &lt;&lt; std::endl;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>4.list、vector、deque、map以及set的使用场景：  </p>
<ul>
<li>list : anytime when a doubly-linked list is required.</li>
<li>vector : anytime when a dynamic array is required.</li>
<li>deque : An answer from Stackoverflow.</li>
<li>map : dictionary.</li>
<li>set : when to keep elements sorted and unique.<br>deque: </li>
</ul>
<blockquote>
<p>When modeling any kind of real-world waiting line: entities (bits, people, cars, words, particles, whatever) arrive with a certain frequency to the end of the line and are serviced at a different frequency at the beginning of the line. While waiting some entities may decide to leave the line…. etc. The point is that you need “fast access” to insert/deletes at both ends of the line, hence a deque.</p>
</blockquote>
<blockquote>
<p>I’m not sure how realistic this is. Consider that you can’t use a deque to model a real world line unless in that line only the last person can leave. Also in this hypothetical line if the third guy from the end wants to leave then everyone behind him better share his opinion because they’ll need to leave too. </p>
</blockquote>
<blockquote>
<p>I working on this right now: I have one program that displays images with 60Hz using OpenGL. Another program decides what should be drawn in the images. Unfortunately this other program occasionally stops for the garbage collection. I use a deque in the display program as a cache for future images. This way I can ensure that there will always be images available even when the garbage collector stops the producer occasionally. </p>
</blockquote>
<p>6.关联容器的迭代器都是双向的  </p>
<p>7.set和map都可以在声明时进行初始化，初始化时提供对应的值或值对即可。  </p>
<p>8.pair类型定义在头文件utility中，一个pair保存两个不同类型的数据成员，分别通过pair.first和pair.second来访问。map的元素即是pair，所以map有点类似于成员为pair是vector,pair的定义方式如下：   </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义一个pair，两个类型分别为T1,T2并使用v1,v2对其进行值初始化。当然也可以使用=号进行初始化或者只定义，但定义时会调用默认初始化  </span></span><br><span class="line"><span class="function">pair&lt;T1, T2&gt; <span class="title">p</span><span class="params">(v1, v2)</span></span>;  </span><br><span class="line"></span><br><span class="line"><span class="comment">//返回一个用v1和v2初始化的pair，pair的类型从v1和v2的类型推断出来  </span></span><br><span class="line"><span class="built_in">make_pair</span>(v1, v2); </span><br></pre></td></tr></table></figure>
<p>C++11中可以让函数直接返回一个pair，即可以使函数一次返回两个值。  </p>
<p>9.关联容器定义了以下额外的类型别名：  </p>
<ul>
<li>key_type 表示容器类型的关键字类型  </li>
<li>mapped_type 表示每个关键字关联的类型，只适用于map</li>
<li>value_type 对于set，与key_type相同，对于map，为pair&lt;const key_type, mapped_type&gt;<br>例如：  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">set&lt;string&gt;::value_type v1;  <span class="comment">//v1是一个string</span></span><br><span class="line">set&lt;string&gt;::key_type v2;  <span class="comment">//v2是一个string</span></span><br><span class="line">map&lt;string, <span class="type">int</span>&gt;::value_type v3;  <span class="comment">//v3是一个pair&lt;const string, int&gt;</span></span><br><span class="line">map&lt;string, <span class="type">int</span>&gt;::key_type v4;  <span class="comment">//v4是一个string</span></span><br><span class="line">map&lt;string, <span class="type">int</span>&gt;::mapped_type v5;  <span class="comment">//v5是一个int</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>10.对一个关联容器迭代器解引用时，会得到一个类型为容器的value_type的值的引用，对于map而言，value_type是一个pair类型，其first成员保存const的关键字，second成员保存值，所以只能通过map迭代器修改pair的值，但不能修改其关键字的值。记得可以使用<code>-&gt;</code>来直接访问引用之后的对象的成员。     </p>
<p>11.set的迭代器虽然定义了iterator和const_iterator，但两种类型都只允许只读访问set中的元素，而不能修改其值。  </p>
<p>12.当使用一个迭代器遍历一个map、multimap、set或multiset时，迭代器按关键字升序遍历元素。   </p>
<p>13.由于关联容器的关键字总是会有const属性，而泛型算法一般需要向元素写入值，所以通常不对关联容器使用泛型算法。  </p>
<p>14.向关联容器中插入元素使用insert和emplace成员函数，删除元素使用erase。向map中添加元素的4种方式，假定word_count存储的是单词和它出现的次数：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">word_count.<span class="built_in">insert</span>(&#123;word, <span class="number">1</span>&#125;); <span class="comment">//C++11中支持的花括号直接初始化</span></span><br><span class="line">word_count.<span class="built_in">insert</span>(<span class="built_in">make_pair</span>(word, <span class="number">1</span>));  <span class="comment">//调用make_pair来返回一个pair</span></span><br><span class="line">word_count.<span class="built_in">insert</span>(<span class="built_in">pair</span>&lt;string, <span class="type">size_t</span>&gt;(word, <span class="number">1</span>));  <span class="comment">//显式构造一个pair</span></span><br><span class="line">word_count.<span class="built_in">insert</span>(map&lt;string, <span class="type">size_t</span>&gt;::<span class="built_in">value_type</span>(word, <span class="number">1</span>));  <span class="comment">//构造一个恰当的pair类型，并构造该类型的一个新对象</span></span><br></pre></td></tr></table></figure>

<p>15.关联容器的insert（或emplace）返回的值依赖与容器类型和参数，对于不包含重复关键字的容器，添加单一元素的insert和emplace版本返回一个pair，该pair的first成员是一个迭代器，指向具有给定关键字的元素；second成员是一个bool值，指出元素是插入成功还是已经存在于容器中。如果关键字已在容器中，则insert什么事情也不做，且返回值中的bool部分为false。如果关键字不存在，元素被插入容器中，且bool值为true。    </p>
<p>15.map和unordered_map容器提供了下标运算符和一个对应的at函数。它们的区别如下：  </p>
<ul>
<li>c[k]  返回关键字为k的元素；如果k不在c中，添加一个关键字为k的元素，对其进行值初始化。  </li>
<li>c.at(k)  访问关键字为k的元素，带参数检查；若k不在c中，抛出一个out_of_range异常。  </li>
</ul>
<p>16.map下标运算符与解引用一个map迭代器所返回的类型是不一样的。当对一个map进行下标操作时，会获得一个mapped_type对象；但当解引用一个map迭代器时，会得到一个value_type对象。     </p>
<p>17.关联容器支持多种元素访问方式，如find成员函数和count成员函数。  </p>
<p>18.map下标操作的作用是：若key存在，则返回相应的value；若key不存在，则对该key对应的value赋一个对应于value类型数据的默认值并返回。例如对于类型为<code>map&lt;string,string&gt;</code>的变量m,如果m中不存在”str”，则当使用m[“str”]时，相当于向m中插入了一个(“str”, “”)  </p>
<p>19.记得使用find进行查找某个值是否在map变量中。  </p>
<p>18.map使用示例:    </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">//搜索input文件中的内容，根据map_file中的文件规则相应简写单词进行替换</span></span><br><span class="line"><span class="comment">//例如input中的某行为ho a y，map_file中的规则有</span></span><br><span class="line"><span class="comment">//ho how</span></span><br><span class="line"><span class="comment">//a are</span></span><br><span class="line"><span class="comment">//y you</span></span><br><span class="line"><span class="comment">//则该行输出应为how are you, 假定规则文件内容都是有效的</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;map&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fstream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sstream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdexcept&gt;</span></span></span><br><span class="line"><span class="comment">//根据文件建立相应map</span></span><br><span class="line"><span class="function">std::map&lt;std::string, std::string&gt; <span class="title">buildMap</span><span class="params">(std::ifstream &amp;mapfile)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    std::map&lt;std::string, std::string&gt; trans_map;</span><br><span class="line">    std::string key;</span><br><span class="line">    std::string value;</span><br><span class="line">    <span class="keyword">while</span> (mapfile &gt;&gt; key &amp;&amp; <span class="built_in">getline</span>(mapfile, value)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (value.<span class="built_in">size</span>() &gt; <span class="number">1</span>)</span><br><span class="line">            trans_map[key] = value.<span class="built_in">substr</span>(<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            <span class="keyword">throw</span> std::<span class="built_in">runtime_error</span>(<span class="string">&quot;no rule for &quot;</span> + key);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> trans_map;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//根据map搜索单词</span></span><br><span class="line"><span class="function"><span class="type">const</span> std::string &amp; <span class="title">transword</span><span class="params">(<span class="type">const</span> std::string &amp;str, <span class="type">const</span> std::map&lt;std::string, std::string&gt; &amp;trans_map)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    std::map&lt;std::string, std::string&gt;::const_iterator it = trans_map.<span class="built_in">find</span>(str);</span><br><span class="line">    <span class="keyword">if</span> (it != trans_map.<span class="built_in">cend</span>())</span><br><span class="line">        <span class="keyword">return</span> it-&gt;second;</span><br><span class="line">    <span class="keyword">else</span> </span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//输出</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">transform</span><span class="params">(std::ifstream &amp;infile, std::ifstream &amp;mapfile)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">auto</span> trans_map = <span class="built_in">buildMap</span>(mapfile);</span><br><span class="line">    std::string line;</span><br><span class="line">    <span class="keyword">while</span> (<span class="built_in">getline</span>(infile, line)) &#123;</span><br><span class="line">        <span class="function">std::istringstream <span class="title">is</span><span class="params">(line)</span></span>;</span><br><span class="line">        std::string str;</span><br><span class="line">        <span class="keyword">while</span> (is &gt;&gt; str) &#123;</span><br><span class="line">            std::cout &lt;&lt; <span class="built_in">transword</span>(str, trans_map) &lt;&lt; <span class="string">&quot; &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        std::cout &lt;&lt; std::endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="function">std::ifstream <span class="title">infile</span><span class="params">(<span class="string">&quot;words.txt&quot;</span>)</span>, <span class="title">mapfile</span><span class="params">(<span class="string">&quot;trans_map.txt&quot;</span>)</span></span>;</span><br><span class="line">    <span class="keyword">if</span> (infile &amp;&amp; mapfile)</span><br><span class="line">        <span class="built_in">transform</span>(infile, mapfile);</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        std::cout &lt;&lt; <span class="string">&quot;Error, Can&#x27;t open the file&quot;</span> &lt;&lt; std::endl;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>9.C++11中定义了4个无序关联容器（unordered associative container）。这些容器不是使用比较运算符来组织元素，而是使用一个哈希函数和关键字类型的==运算符。有序与无序关联容器的对比如下：  </p>
<ul>
<li>Ordered Associative Container<ul>
<li>Standard Traversal encounters elements in sorted order</li>
<li>Order predicate may be specified</li>
<li>Default order predicate is “less than”, defined using operator<code>&lt;</code> for the element type</li>
<li>Popular implementations: OrderedVector, BinarySearchTree</li>
<li>Search operations required to have O(log n) runtime</li>
<li>Insert, Remove operations should either be seldom used or have O(log n) runtime</li>
</ul>
</li>
<li>Unordered Associative Container<ul>
<li>Standard Traversal encounters elements in unspecified order</li>
<li>Search, Insert, Remove operations should have average-case constant runtime</li>
<li>Popular implementations use hashing</li>
</ul>
</li>
</ul>

    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Notes/" rel="tag"># Notes</a>
              <a href="/tags/CPP/" rel="tag"># CPP</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2015/06/11/CUDA-study-notes/" rel="prev" title="CUDA学习笔记">
      <i class="fa fa-chevron-left"></i> CUDA学习笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2015/08/12/Determine-block-size/" rel="next" title="Streaming MultiProcessor、Register、Shared-Memory对线程块尺寸的影响">
      Streaming MultiProcessor、Register、Shared-Memory对线程块尺寸的影响 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E6%9C%AC%E6%96%87"><span class="nav-number">1.</span> <span class="nav-text">关于本文</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86"><span class="nav-number">2.</span> <span class="nav-text">基础知识</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#string"><span class="nav-number">3.</span> <span class="nav-text">string</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#C-11%E4%B8%8B%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%95%B0%E7%BB%84"><span class="nav-number">3.1.</span> <span class="nav-text">C++11下的字符串数组</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#vector"><span class="nav-number">4.</span> <span class="nav-text">vector</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8iterator"><span class="nav-number">5.</span> <span class="nav-text">迭代器iterator</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%8C%87%E9%92%88"><span class="nav-number">6.</span> <span class="nav-text">指针</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E7%BB%84%E4%B8%8E%E6%8C%87%E9%92%88"><span class="nav-number">6.1.</span> <span class="nav-text">数组与指针</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E7%BB%B4%E6%95%B0%E7%BB%84%E4%B8%8E%E6%8C%87%E9%92%88"><span class="nav-number">6.2.</span> <span class="nav-text">多维数组与指针</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%92%8C%E8%AF%AD%E5%8F%A5"><span class="nav-number">7.</span> <span class="nav-text">表达式和语句</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#sizeof"><span class="nav-number">7.1.</span> <span class="nav-text">sizeof</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="nav-number">7.2.</span> <span class="nav-text">强制类型转换</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%82%E5%B8%B8"><span class="nav-number">7.3.</span> <span class="nav-text">异常</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%87%BD%E6%95%B0"><span class="nav-number">8.</span> <span class="nav-text">函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#C-%E8%B0%83%E8%AF%95%E5%B8%AE%E5%8A%A9%E5%A4%B4%E6%96%87%E4%BB%B6cassert"><span class="nav-number">8.1.</span> <span class="nav-text">C++调试帮助头文件cassert</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E6%8C%87%E9%92%88"><span class="nav-number">8.2.</span> <span class="nav-text">函数指针</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%B1%BB"><span class="nav-number">9.</span> <span class="nav-text">类</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-number">9.1.</span> <span class="nav-text">构造函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%8B%E5%85%83"><span class="nav-number">9.2.</span> <span class="nav-text">友元</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%A0%87%E5%87%86IO%E5%BA%93"><span class="nav-number">10.</span> <span class="nav-text">标准IO库</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E7%9A%84%E8%BE%93%E5%85%A5%E5%92%8C%E8%BE%93%E5%87%BA"><span class="nav-number">10.1.</span> <span class="nav-text">文件的输入和输出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%B5%81"><span class="nav-number">10.2.</span> <span class="nav-text">字符串流</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%A1%BA%E5%BA%8F%E5%AE%B9%E5%99%A8"><span class="nav-number">11.</span> <span class="nav-text">顺序容器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%B9%E5%99%A8%E9%80%82%E9%85%8D%E5%99%A8"><span class="nav-number">11.1.</span> <span class="nav-text">容器适配器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%B3%9B%E5%9E%8B%E7%AE%97%E6%B3%95"><span class="nav-number">12.</span> <span class="nav-text">泛型算法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="nav-number">12.1.</span> <span class="nav-text">lambda表达式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#iterator"><span class="nav-number">12.2.</span> <span class="nav-text">iterator</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%B3%E8%81%94%E5%AE%B9%E5%99%A8"><span class="nav-number">13.</span> <span class="nav-text">关联容器</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="blueyi"
      src="/images/default_avatar.jpg">
  <p class="site-author-name" itemprop="name">blueyi</p>
  <div class="site-description" itemprop="description">心怀善意，虛怀若谷！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">104</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">68</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/blueyi" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;blueyi" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://maxwi.com/" title="http:&#x2F;&#x2F;maxwi.com" rel="noopener" target="_blank">Maxwi</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2014 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">blueyi</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="Symbols count total">750k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">11:22</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '0f8243eb2c8b2207980f',
      clientSecret: 'd159633a33519d3b7a48b0ca729032f7d1f38a41',
      repo        : 'notes',
      owner       : 'blueyi',
      admin       : ['blueyi'],
      id          : '679f5d393f07c9a2a10841e1c73954f4',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

    </div>
</body>
</html>
